c++ deep copy vector code example

Example 1: deep copy c++

// DEEP COPY
class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Example 2: copy a part of a vector in another in c++

// Copying vector by copy function 
copy(vect1.begin(), vect1.end(), back_inserter(vect2));

Example 3: deep copy c++

//SHALLOW COPY
class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Tags:

Cpp Example