The smart way to create a class member is std :: vector <std :: unique_ptr <AClass>>
This question combines unique_ptr as a member of the class and the transfer semantics cannot be compiled using clang and C ++ std :: vector in the constructor .
My goal is to create a shell
struct V_wrapper{ std::vector<std::unique_ptr<AClass> > vec; V_wrapper(std::vector<std::unique_ptr<AClass> > v) : vec{std::move(v)} {} }; Unfortunately, this code does not compile because the compiler (clang Apple LLVM version 4.2) tries to copy the construction of the vector v , which is not supported. On the other hand, if I create an intermediate wrapper for std::unique_ptr<AClass> , as follows
struct P_wrapper{ std::unique_ptr<AClass> Ptr; P_wrapper(std::unique_ptr<AClass>& p) : Ptr(std::move(p)) {} }; and write V_wrapper as follows
struct V_wrapper{ std::vector<P_wrapper > vec; V_wrapper(std::vector<P_wrapper > v) : vec{std::move(v)} {} }; then I have no problem. I think (emphasis) that the reason for this is that the vector constructor understands that you should use the link to move, not copy, as in unique_ptr as a member of the class and move semantics cannot be compiled with clang .
Unfortunately, this leads to a rather inconvenient build procedure, which I do std::vector<std::unique_ptr<AClass> > , use it to build P_wrapper and finally use it to build V_wrapper . I feel that the average step should be completely redundant! In addition, the interface greatly complicates the reading. The whole point of the wrapper was primarily to hide the vec implementation from the user, and now there is an inexplicable (without knowing the source code) P_wrapper object, which is used only to create another object ....
I want to avoid this and have only one shell. Is there a way to cut out the average person so that I can return to the first, much simpler implementation of V_wrapper ?
Do not use latches without fixing; std::vector has a constructor that consumes initializer lists. The obvious way to write this compiler for me is:
#include <memory> // for std::unique_ptr #include <utility> // for std::move #include <vector> // for std::vector struct bar {}; struct foo { using vtype = std::vector<std::unique_ptr<bar>>; foo(vtype v) : _v(std::move(v)) { } private: vtype _v; }; You need to remove the default constructor and assignment operators. These functions are defined implicitly and must be explicitly deleted as they try to copy the vector and its contents (which is an illegal operation in unique_ptr ).
struct V_wrapper { public: V_wrapper(std::vector<std::unique_ptr<AClass> > v) : vec(std::move(v)) {} // Delete default copy constructor + assignment operator V_wrapper(const V_wrapper &) = delete; V_wrapper& operator= (const V_wrapper &) = delete; private: std::vector<std::unique_ptr<AClass> > vec; };