std :: vector :: push_back Ein nicht kopierbares Objekt gibt einen Compilerfehler aus

Ich bekomme Kompilierungsfehler aufg++ (GCC) 4.7.2 aber nicht aufMSVC-2012 wenn ich es versuchestd::vector::push_back Ein nicht kopierbares (privater Kopierkonstruktor), aber verschiebbares Objekt. Für mich sieht mein Beispiel mit vielen anderen Beispielen auf SO und anderswo identisch aus. Die Fehlermeldung lässt darauf schließen, dass die Struktur nicht direkt konstruierbar ist. Ich weiß nicht, was dies bedeutet. Daher bin ich mir doppelt unsicher, warum ein Objekt direkt konstruierbar sein muss, um zurückgeschoben zu werden.

#include <vector>
#include <memory>

struct MyStruct
{

    MyStruct(std::unique_ptr<int> p);
    MyStruct(MyStruct&& other);
    MyStruct&  operator=(MyStruct&& other);

    std::unique_ptr<int> mP;

private:
            // Non-copyable
    MyStruct(const MyStruct&);
    MyStruct& operator=(const MyStruct& other);
};

int main()
{

    MyStruct s(std::unique_ptr<int>(new int(5)));
    std::vector<MyStruct> v;

    auto other = std::move(s);       // Test it is moveable
    v.push_back(std::move(other));   // Fails to compile

    return 0;
}

Gibt Fehler

/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/type_traits: In instantiation of ‘struct std::__is_direct_constructible_impl<MyStruct, const MyStruct&>’:
... snip ...
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:900:9:   required from ‘void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = MyStruct; _Alloc = std::allocator<MyStruct>; std::vector<_Tp, _Alloc>::value_type = MyStruct]’
main.cpp:27:33:   required from here
main.cpp:16:5: error: ‘MyStruct::MyStruct(const MyStruct&)’ is private

Einfache Problemumgehung aus verschiedenen Antworten:

BenutzenMyStruct(const MyStruct&) = delete; anstattprivate ctor hackenErbenboost::noncopyable (oder eine andere Klasse mit privatem ctor)

Antworten auf die Frage(1)

Ihre Antwort auf die Frage