Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, how to correctly copy std::vector<Class *> in copy constructor?

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?

like image 220
Vyktor Avatar asked Jan 14 '12 21:01

Vyktor


1 Answers

The data() is not necessary because that will be done automatically to the vector before the constructor is entered. You only need to initialise members that are POD (plain old data) types or types which have no default constructor (or references, constants, etc).

You can initialise the vector with the number of elements that the other one has, so that the vector doesn't have to resize itself as it grows. If you don't, you're starting with a small vector and making it incrementally reach the destination size via allocations and reallocations. This will make the vector the correct size from the very beginning:

B::B(const B& orig) : data(orig.data.size()) {
    for (std::size_t i = 0; i < orig.data.size(); ++i)
        data[i] = new A(*orig.data[i]);
}

Notice that you are not using push_back any more because the vector is already full of orig.data.size() number of elements that are default constructed (which is NULL in the case of pointers).

This also trims down the code because you can use an integer to iterate it instead of an iterator.

If you really want to use iterators, you can do

B::B(const B& orig) : data(orig.data.size()) {
    // auto is preferable here but I don't know if your compiler supports it
    vector<A*>::iterator thisit = data.begin();
    vector<A*>::const_iterator thatit = orig.data.cbegin();

    for (; thatit != orig.data.cend(); ++thisit, ++thatit)
        *thisit = new A(**thatit);
}

The advantage of this is that it will work with other container types (like list) by just changing the types of the iterators (but of course that would go away if you have auto).

If you want to add exception-safety, you need a try/catch block:

B::B(const B& orig) : data(orig.data.size()) {
    try {
        // auto is preferable here but I don't know if your compiler supports it
        vector<A*>::iterator thisit = data.begin();
        vector<A*>::const_iterator thatit = orig.data.cbegin();

        for (; thatit != orig.data.cend(); ++thisit, ++thatit)
            *thisit = new A(**thatit);
    } catch (...) {
        for (vector<A*>::iterator i = data.begin(); i != data.end(); ++i)
            if (!*i)
                break;
            else
                delete *i;

        throw;
    }
}

This way you will not have a memory leak if one of the new calls throws an exception. Of course you can use the try/catch along with the way without iterators if you'd rather do it that way.

like image 136
Seth Carnegie Avatar answered Sep 21 '22 17:09

Seth Carnegie