删除在C ++中传递给成员函数的新对象

时间:2018-05-15 00:13:14

标签: c++

只是试图绕过我如何释放作为参数传递的新对象的内存。

假设我有一个像这样定义的Link类:

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;
};

然后我就像这样定义Link * Insert(Link *):

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;
}

然后在我的main()中,我执行以下操作:

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"));
}

我创建了一个名为“Cars”的链接指针,并在堆上分配了一个值为“Ford”的新链接。然后我将我的Cars指针指向从Insert()返回的新链接。再重复此步骤2次。

我的问题是,当我将新的Link对象作为参数传递时,如何删除或释放分配的内存?我是否在Link的析构函数中这样做?如果我只删除我的汽车指针,它就不会释放其他链接。

1 个答案:

答案 0 :(得分:4)

使用智能指针,所有权将很明确:

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"));
}