ryani42
ryani42

Reputation: 111

Garbage collection when using clone

Im writing a program which uses the following clone() method:

circuit* circuit::clone()
{
    return new circuit(*this);
}

It is used in my copy constructor as so:

circuit::circuit(const circuit& circ)
{
    rank = circ.rank;
    branch_info = circ.branch_info;
    for (int i{ 0 }; i < circ.components.size(); i++) {
        components.push_back(circ.components[i]->clone());
    }
    for (int i{ 0 }; i < circ.branches.size(); i++) {
        branches.push_back(circ.branches[i]->clone());
    }
}

My question is, using this implementation, how do I ensure that there are no memory leaks as I cannot delete them within this function. Is there a way to implement it in the destructor or something along them lines?

Upvotes: 0

Views: 73

Answers (1)

Homer512
Homer512

Reputation: 13417

Modern C++ (meaning C++11 upwards) comes with a unique_ptr type that does exactly that. Use it like this:

std::unique_ptr<circuit> circuit::clone() const
{
    return std::make_unique<circuit>(*this);
}

std::vector<std::unique_ptr<circuit>> components, branches;

circuit::circuit(const circuit& circ)
: rank(circ.rank),
  branch_info(circ.branch_info)
{
    for(const std::unique_ptr<circuit>& component: circ.components)
        components.push_back(component->clone());
    for(const std::unique_ptr<circuit>& branch: circ.branches)
        branches.push_back(branch->clone());
}

Compile with C++14 or upwards.

Upvotes: 1

Related Questions