Not copied elements in vector

I have a class that cannot be copied (that is, the copy constructor and assignment operator are marked as "delete"). I would like to save them in std :: vector.

This is a RAII class, so just storing a pointer or a reference to it is not what I'm looking for.

My knowledge of the new initializer lists and move constructors is somewhat limited, is this possible?

+7
c ++ c ++ 11 move-semantics stl
source share
2 answers

Yes, you can have std::vector<NotCopyable> if NotCopyable is movable:

 struct NotCopyable { NotCopyable() = default; NotCopyable(const NotCopyable&) = delete; NotCopyable& operator = (const NotCopyable&) = delete; NotCopyable(NotCopyable&&) = default; NotCopyable& operator = (NotCopyable&&) = default; }; int main() { std::vector<NotCopyable> v; NotCopyable nc; v.push_back(NotCopyable{}); v.emplace_back(); v.push_back(std::move(nc)); } 

Living example .

+10
source share

As long as the elements are movable, yes, just save them in the vector.

+2
source share

All Articles