简体   繁体   中英

Deleting new object passed to member function in C++

just trying to wrap my head around how I go about deallocating memory of new objects which are passed as arguments.

Say I have a Link class defined like this:

class Link{
public:
    Link(const std::string& value, Link* previous = nullptr, Link* successor = nullptr) : _value{ value }, _previous{ previous }, _successor{ successor }{}

    Link* Insert(Link* new_link);

    Link* getPreviousLink() const{ return _previous; }
    Link* getSuccessorLink() const{ return _successor; }

    std::string _value;
private:
    Link* _previous;
    Link* _successor;
};

And then I have Link* Insert(Link*) defined like so:

Link* Link::Insert(Link* new_link){
    if(!new_link){ return this; }
    if(!this){ return new_link; }
    new_link->_successor = this;
    if(_previous){ _previous->_successor = new_link; }
    new_link->_previous = _previous;
    _previous = new_link;
    return new_link;
}

And then in my main(), I do the following:

int main(){
    Link* Cars = new Link("Ford");
    Cars = Cars->Insert(new Link("Ferrari"));
    Cars = Cars->Insert(new Link("Hummer"));
    Cars = Cars->Insert(new Link("Volvo"));
}

I've created a Link pointer called 'Cars' and allocated a new Link on the heap with a value of "Ford". I then assign my Cars pointer to a new Link returned from Insert(). Repeat this step 2 more times.

My question is, how do I delete or free the memory allocated when I pass the new Link objects as arguments? Do I do so in the destructor of Link? If I just delete my Cars pointer, it wouldn't deallocate the other Links.

With smart pointer, ownership would be clear:

class Link : public std::enable_shared_from_this<Link> {
public:
    Link(const std::string& value) : _value{ value } {}

    std::shared_ptr<Link> Insert(std::shared_ptr<Link> new_link);

    std::shared_ptr<Link> getPreviousLink() const{ return _previous.lock(); }
    std::shared_ptr<Link> getSuccessorLink() const{ return _successor; }

    std::string _value;
private:
    std::weak_ptr<Link> _previous;
    std::shared_ptr<Link> _successor;
};

std::shared_ptr<Link> Link::Insert(std::shared_ptr<Link> new_link)
{
    if (!new_link){ return shared_from_this(); }
    new_link->_successor = shared_from_this();
    auto prev = _previous.lock();
    if (prev) { prev->_successor = new_link; }
    new_link->_previous = prev;
    _previous = new_link;
    return new_link;
}

int main(){
    auto Cars = std::make_shared<Link>("Ford");
    Cars = Cars->Insert(std::make_shared<Link>("Ferrari"));
    Cars = Cars->Insert(std::make_shared<Link>("Hummer"));
    Cars = Cars->Insert(std::make_shared<Link>("Volvo"));
}

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