与升压:: shared_ptr的(相对于复位()函数)分配问题 [英] question on assignment with boost::shared_ptr (vs. the reset() function)

查看:174
本文介绍了与升压:: shared_ptr的(相对于复位()函数)分配问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是明确地回答了什么地方,但我由升压文档和文章,我在网上看了有点糊涂了。

Sorry if this is explicitly answered somewhere, but I'm a little confused by the boost documentation and articles I've read online.

我知道我可以使用reset()函数来一个shared_ptr内释放内存(假设引用计数为零),如,

I see that I can use the reset() function to release the memory within a shared_ptr (assuming the reference count goes to zero), e.g.,

shared_ptr<int> x(new int(0));
x.reset(new int(1));

此,相信会导致产生两个整型对象,并且由这两条线的端部的整数等于零会从存储器中删除。

This, I believe would result in the creation of two integer objects, and by the end of these two lines the integer equaling zero would be deleted from memory.

但是,如果我用code以下块:

But, what if I use the following block of code:

shared_ptr<int> x(new int(0));
x = shared_ptr<int>(new int(1));

显然,现在* X == 1是真的,但将原来的整数对象(等于零)可以从内存中删除或者泄露我内存?

Obviously, now *x == 1 is true, but will the original integer object (equaling zero) be deleted from memory or have I leaked that memory?

在我看来,这将是赋值运算符降低的shared_ptr的引用计数的问题,但在源$ C ​​$ C一目了然似乎并不清楚这个问题了我。希望更有经验的人或有知识能帮助我。先谢谢了。

It seems to me that this would be an issue of the assignment operator decreasing the shared_ptr's reference count, but a glance at the source code doesn't seem to clear the question up for me. Hopefully someone more experienced or knowledgeable can help me out. Thanks in advance.

推荐答案

该文档是相当明确的:

的shared_ptr和放大器;运算符=(常量的shared_ptr和放大器; R); //不会抛出

效果:相当于的shared_ptr(R).swap(*此)

所以它只是交换与您共创临时对象所有权。临时然后到期,降低的引用计数。 (和释放,如果为零。)

So it just swaps ownership with the temporary object you create. The temporary then expires, decreasing the reference count. (And deallocating if zero.)

这些容器的目的是为了不泄漏内存。所以,不,你不必担心漏水的事,除非你想误事的目的了。 (换句话说,你可能不需要怀疑升压知道他们在做什么。)

The purpose of these containers is to not leak memory. So no, you don't need to worry about leaking things unless you're trying to mess things up on purpose. (In other words, you probably don't need to doubt Boost knows what they're doing.)

这篇关于与升压:: shared_ptr的(相对于复位()函数)分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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