为什么共享指针分配“交换"? [英] Why shared pointer assignment does 'swap'?

查看:53
本文介绍了为什么共享指针分配“交换"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,分配共享的ptr时的行为应类似于:

As i understand when assigned shared ptr should behave like:

a) if(--this-> count == 0){释放this-> count和this-> obj}

b) this-> count = r-> count,this-> obj = r-> obj;

助推器只是

shared_ptr & operator=( shared_ptr const & r ) BOOST_NOEXCEPT
{
    this_type(r).swap(*this);
    return *this;
}

那么交换背后的魔力是什么?为什么它起作用?

So what is the magic behind swap and why this works?

推荐答案

a)if(--this-> count == 0){释放this-> count和this-> obj}

a) if (--this->count == 0) { release this->count and this->obj }

否, shared_ptr 保留两个计数,一个计数用于对象,一个计数用于包含参考计数的控制块.在第一个达到零时释放 this-> obj ,在第二个达到零时释放 this-> count (和第二个计数).

No, a shared_ptr keeps two counts, one for the object and one for the control block containing the reference counts. You release this->obj when the first one reaches zero and releases this->count (and the second count) when the second one reaches zero.

b)this-> count = r-> count,this-> obj = r-> obj;

b) this->count = r->count, this->obj = r->obj;

否,您缺少参考计数的增量.另外,正如Yakk的答案所指出的那样,您必须检查自分配或首先增加右侧,以避免在自分配时错误地破坏对象.

No, you're missing a reference count increment. Also, as Yakk's answer points out, you must either check for self-assignment or increment the right side first, to avoid incorrectly destroying the object on self-assignment.

因此,您的理解是不完整/不正确的,但是如果您按照Boost代码进行操作,则会发现它确实做对了.它会增加 r 对象上的引用计数,交换所有必要的值,然后减少 * this 的原始值上的引用计数.

So your understanding is incomplete/incorrect, but if you follow through the Boost code you'll see it does exactly the right thing. It increases the reference count on the r object, exchanges all the necessary values, then decreases the reference count on the original value of *this.

增加引用计数的步骤已经在复制构造函数中实现,因此可以重复使用.

The step of increasing the reference count is already implemented in the copy constructor, so it re-uses that.

交换所有必要值的步骤已经在 swap 成员中实现,因此它可以使用它.

The step of exchanging all the necessary values is already implemented in the swap member, so it uses that.

减少引用计数(并在需要时释放任何内容)的步骤已经由析构函数完成,因此它可以使用.

The step of decreasing the reference counts (and freeing anything if required) is already done by the destructor, so it uses that.

这是极好的代码重用.另一种选择是重复所有与复制构造函数,交换成员和析构函数中发现的相同的代码,这将是多余的并且容易出错.

This is excellent code re-use. The alternative would be to repeat all the same code as is found in the copy constructor, swap member and destructor, which would be redundant and error-prone.

这篇关于为什么共享指针分配“交换"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆