From std::vector , describing T :
The requirements for the elements depend on the actual operations performed on the container. Typically, an element type is required to meet the requirements of MoveConstructible and MoveAssignable, but many member functions have more stringent requirements.
CanNotCopy not movable or copied, so it cannot be used as T
A particular solution is to use std::reference_wrapper<CanNotCopy> as the type of element (which can be copied, but not by default), which:
... is a class template that wraps the link in the copy to be assigned to the object. It is often used as a mechanism for storing links inside standard containers (for example, std :: vector or std :: pair), which usually cannot contain links.
For instance:
std::vector<std::reference_wrapper<CanNotCopy>> hoge; int j = 19; CanNotCopy c(j); hoge.push_back(std::ref(c)); std::cout << hoge[0].get().intref_ << "\n";
resize() not available with std::reference_wrapper<CanNotCopy> because it is not constructive by default. However, this solution is fragile, as there are time-dependent references to CanNotCopy and int that are referenced within the CanNotCopy instance, putting the links at risk.
The solution is to use std::unique_ptr<CanNotCopy> as the element type (which is movable and default constructive):
std::vector<std::unique_ptr<CanNotCopy>> hoge; hoge.resize(5); int j = 19; hoge[1].reset(new CanNotCopy(j)); std::cout << hoge[1]->intref_ << "\n";
The dependency of the service life on the int link inside CanNotCopy is still preserved.
source share