Replacement for vector accepting non standard constructable and not assignable types
I have a class test
which isn't standard constructable nor assignable due to certain reasons. However it is copy constructable - on may say it behaves a bit like a reference.
Unfortunately I needed a dynamic array of these elements and realized that vector<test>
isn't the right choice because the elements of a vector must be standard constructable and assignable. Fortunately I got around this problem by
- using
vector<T>::reserve
andvector<T>::push_back
instead ofvector<T>::resize
and direct filling the entries (no standard construction) the copy'n'swap trick for assignment and the fact that a
vector
is usually implemented using the Pimpl-idiom (no direct assignment of an existingtest
element), i.eclass base { private: std::vector<test> vect; /* ... */ public: /* ... */ base& operator= (base y) { swap(y); return *this; } void swap(base& y) { using std::swap; swap(vect, y.vect); } /* ... */ };
Now I assume that I probably didn't considered every tiny bit and above all these tricks are strongly implementation dependent. The standard only guarantees standard behavior for standard constructable and assignable types.
Now 开发者_运维知识库what's next? How can I get a dynamic array of test
objects?
Remark: I must prefer built in solutions and classes provided by the standard C++.
Edit: I just realized that my tricks actually didn't work. If I define a really* non assignable class I get plenty of errors on my compiler. So the question condenses to the last question: How can I have a dynamic array of these test
objects?
(*) My test
class provided an assignment operator but this one worked like the assignment to a reference.
Edit: The below is no longer good practice. If your object supports moving then it will probably fit into a vector (see the std::vector
elements requirements for details, in particular the changes for C++17).
Consider using Boost's ptr_vector, part of the Boost Pointer Container Library. See in particular advantage #3 in that library's motivation.
How about using a vector of pointers?
Write your own dynamic array class. Sounds like less work than trying to make the STL one work with that strange type.
You might want to look at Boost.Intrusive -- although that would mean you would need to change the type of test
and where in memory you put the instances of test
.
精彩评论