user13555740
user13555740

Reputation:

Deep Copy Pointer and Delete the Memory

I'm trying to create Copy Constructor.

For example, There is a class like :

#include <string>
#include <vector>
using namespace std;
class Test
{
    vector<string*> name;
public:
    ~Test();
    Test(const string& name);
    Test(const Test& t);
};

Test::Test(const Test& t)
{
    for (auto it = t.name.begin(); it != t.name.end(); it++) {
        this->name.push_back((*it));
    }
}

Test::Test(const string& name)
{
    this->name.emplace_back(name);
}

Test::~Test() {
    for (auto it = name.begin(); it != name.end(); it++) {
        delete (*it);
        (*it) = nullptr;
    }
}

int main() {
    Test t("Hello World!");
    Test t2(t);
}

When program is done, then error occured: Access violation reading location 0xDDDDDDDD

I know that, it is because of t's name has deleted when t2 is called, however I don't know how to deep-copy of the name vector.

Thank you for your help.

Upvotes: 0

Views: 308

Answers (1)

molbdnilo
molbdnilo

Reputation: 66451

In order to make a deep copy, you need to copy what any pointer points to.
Like this:

name.push_back(new string(**it));

You also need to implement the copy assignment operator.

Upvotes: 5

Related Questions