简体   繁体   中英

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 it job, but I'm finding to way how to reach the total perfection in this.

At first :data() - is this initialization required to initialize empty vector correctly (and it's part of writing a good and clean code)?

How to use vector::iterator in copy constructor, the only way I found is the one I've written into code (const should be mandatory for copy constructor).

Copying just vector would copy just pointer values and not whole objects?

And finally new data initialization... Is there any way how could I replace the whole loop with smaller piece of code and/or is there any standard how to write copy constructor for std::containers which contains 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...)

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 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 do that, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM