I'm using this two classes
// This is generic data structure containing some binary data
class A {
public:
A();
A(const A&);
~A();
}
// Main data container
class B {
public:
B();
B( const B&);
~B();
protected:
std::vector<A *> data;
}
// Copy constructor for class b
B::B( const B& orig):data() {
for( std::vector<A *>::const_iterator it = orig.data.begin();
it < orig.data.end(); ++it){
data.push_back( new A( *(*it)));
}
}
I guess this class would do its job, but I'm looking for a way to reach total perfection.
First, :data()
- is this initialization required to initialize empty vector correctly (is it clean code)?
How is vector::iterator
used in copy constructor? The only way I found is the one I've written into code (const should be mandatory for copy constructor).
Does copying the vector copy pointer values and not whole objects?
And finally new data initialization... Is there any way to replace the whole loop with less code and/or is there any standard how to write copy constructor for std::containers which contain object pointers?
Sub question: I'm assuming using vector<A *>
is much more suitable and effective for various reasons than just vector<A>
(not copying every time, power to decide whether (not) to copy objects...) Is this assumption correct?
data
in initializer list. Usingpush_back()
like that is very ineffective. – Warmupstd::deque
of objects is usually better. (Also, for small objects, a vector of pointers is typically slower than a vector of objects; too many indirections and calls to new/delete) – Kelsy