std :: vector :: push_back не копируемый объект выдает ошибку компилятора
Я получаю ошибки компиляции наg++ (GCC) 4.7.2
но не наMSVC-2012
при попыткеstd::vector::push_back
не копируемый (конструктор частного копирования), но перемещаемый объект. Для меня мой пример выглядит идентично многим другим примерам на SO и в других местах. Сообщение об ошибке делает его похожим на проблему с тем, что структура не является «прямой конструкцией» - я не знаю, что это значит, поэтому вдвойне не уверен, почему объект должен быть «прямой конструкцией», чтобы быть отодвинутым назад.
#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;
}
Дает ошибки
/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
Простой обходной путь из различных ответов:
использованиеMyStruct(const MyStruct&) = delete;
вместоprivate ctor
мотыгаунаследоватьboost::noncopyable
(или другой класс с частным ctor)