For customized use, I have inherited std::vector to a custom class Vector. For my requirement this public inheritance is ok.
One intention is to avoid making copies of a vector array multiple times, so I decided this custom class to be ‘ownership’ based.
Vector<A> vA1(100); // vA1 is allocated A[100]
Vector<A> vA2 = vA1; // vA2 refers to original A[100] and ...
// ... vA1 is now blank which is expected
This is how it’s implemented for C++03:
template<typename T>
struct Vector : std::vector<T>
{
// ... other constructors
Vector (const Vector ©) // copy constructor
{
this->swap(const_cast<Vector&>(copy)); // <---- line of interest
}
// 'operator =' is TBD (either same as above or unimplemented)
};
Am I breaking any language rule/feature/convention ? Is there anything bad in this code ?
Edit: I have added my new approach in form of answer below (Here is its working demo).
With the insight from comments/answers, I realized that my current approach is not a good idea to deal with the things.
I have come up with a changed designed where I try to simulate the “move” operation using
swap()method (consider them interchangeable in this context).For any class or container, which wants to make faster copying (i.e. move by swapping) should inherit below class (directly copy pasting from the real file):
Here how it’s supposed to be deployed:
Here how it’s supposed to be used: