Std :: vector <Foo> when some members of Foo are links
I often prefer to use references than pointers when possible, this makes the syntax cleaner in my opinion. In this case, I have a class:
class Foo { public: Foo(Bar & bar) : bar_(bar) {} private: Bar & bar_; }; operator=() implicitly deleted by the compiler for such a class, since after setting the link it cannot be changed (I can technically define my own, which does not change bar_, but this would not be the required behavior, so I would prefer the compiler complaining, if I try to assign foo).
I need std::vector<Foo> v; . This is not possible before C ++ 11, since the template parameter must be CopyAssignable. Indeed, when I call v.push_back(Foo(bar)); , the compiler complains. But I believe this is possible since C ++ 11 and Move semantics.
My question is: is there a workaround using C ++ 11 that would make it possible to create such a vector, or am I stuck in this case and cannot use pointers instead of links? If there is a workaround, I really appreciate the code snippet, as I am not familiar with the semantics of movement.
Voila emplace_back can do this job due to perfect forwarding.
#include <vector> class Bar{}; class Foo { public: Foo(Bar & bar) : bar_(bar) {} private: Bar & bar_; }; using namespace std; int main() { vector<Foo> v; Bar bar; v.emplace_back(bar); } You can also save the link yourself in a container with std::reference_wrapper used as std::vector<std::reference_wrapper<int>> v
Use v.emplace_back(bar) instead of push_back . It will build Foo in place in the vector memory allocated for it, which does not require copying. Just pass emplace_back arguments to build Foo .
The container template parameter should not be CopyAssignable, it depends on what operations you perform in your container, and if you really use an operation that requires CopyAssignable or MoveAssignable, you cannot use the link as you want (even with move semantics). But if you use only other operations (see Standard), everything will be fine. Some operations require only CopyInsertable, MoveInstable and / or EmplaceConstructible.