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

14,352

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.

Share:
14,352
Vyktor
Author by

Vyktor

"I've been using VIM for 2 years now; mostly because I can't figure out how to turn it off." Started with html, php and C++. Now working with C, C#, python and doing some reverse engineering.

Updated on July 19, 2022

Comments

  • Vyktor
    Vyktor almost 2 years

    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?

  • someguy
    someguy over 12 years
    You need to dereference orig.data[i].
  • Emil Styrke
    Emil Styrke over 12 years
    One more thing to take into consideration is error handling: what happens if one of the news fail in the middle of the loop? Probably the program will just terminate, but if the out of memory error is handled further up in the call stack you'll have a memory leak.
  • Seth Carnegie
    Seth Carnegie over 12 years
    @EmilStyrke please review my latest edit to see if that handles the situation you are talking about.
  • someguy
    someguy over 12 years
    @Seth Carnegie: You just need to add a little check in case *i is a null pointer (in which case you would just break out of the loop) :)
  • Seth Carnegie
    Seth Carnegie over 12 years
    @someguy why (besides efficiency)?
  • someguy
    someguy over 12 years
    @Seth Carnegie: because copying the vector may have failed half way, so the other half would be null pointers
  • Seth Carnegie
    Seth Carnegie over 12 years
    @someguy yes but it would still work fine (although doing a little extra work) so it's not absolutely necessary. I will add it though since it would be more efficient.
  • someguy
    someguy over 12 years
    @Seth Carnegie: Deleting a null pointer results in undefined behaviour. Also, you don't need to set *i to NULL.
  • Seth Carnegie
    Seth Carnegie over 12 years
    @someguy actually calling delete on a null pointer is defined to do nothing. Not sure why I set *i to null, seemed like a good idea at the time :) At least now I can get rid of the curly braces.
  • someguy
    someguy over 12 years
    @Seth Carnegie: Oh yeah you're right. I think I got it mixed up with dereferencing a null pointer :p.
  • Emil Styrke
    Emil Styrke over 12 years
    @SethCarnegie: Looks like it handles the case I had in mind, yes.