简体   繁体   English

使用默认构造函数提升shared_ptr

[英]boost shared_ptr use with default constructor

I think I might need to do something like the following pseudo-code in my application: 我想我可能需要在我的应用程序中执行类似下面的伪代码:

boost::shared_ptr<T> p;
...
...
p = boost::shared_ptr<T>(new T);

I realize there are other options for using the assignment operator, but I noticed in the boost::shared_ptr documentation/example that they never discussed a case like this one involving the default constructor. 我意识到使用赋值运算符还有其他选项,但我注意到在boost::shared_ptr文档/示例中,他们从未讨论过像这样涉及默认构造函数的情况。

My question I suppose, is: is this valid use? 我想我的问题是:这是否有效使用? In other words, is it legal and could it lead to potential memory leaks? 换句话说,它是否合法,是否会导致潜在的内存泄漏? Appreciate any ideas/corrections. 欣赏任何想法/更正。 Thanks much! 非常感谢!

NOTE: I do recall reading, as also some comments below suggest, that they recommend to always use a named shared_ptr when invoking the constructor with new . 注意:我确实记得阅读,以及下面的一些评论建议,他们建议在使用new调用构造函数时始终使用命名的shared_ptr Still, I find it hard to imagine this might cause any harm. 尽管如此,我发现很难想象这可能会造成任何伤害。 Kindly post any counter-examples if you have them. 如果您有任何反例,请发布任何反例。 Thanks! 谢谢!

It is perfectly legal and memory safe. 它完全合法且内存安全。 The fact that you are invoking the default constructor on T is irrelevant: as long as you have a dynamically allocated object, you can wrap it in a shared_ptr<> 您在T上调用默认构造函数的事实是无关紧要的:只要您有一个动态分配的对象,就可以将其包装在shared_ptr<>

If you refer to the default constructor of shared_ptr<> that's fine too: the wrapped pointer is NULL, which will not be deleted when the other shared_ptr<> is assigned 如果你引用shared_ptr<>的默认构造函数也没关系:包装指针是NULL,当分配了另一个shared_ptr<>时,它不会被删除

You will have to be careful, though to check whether the contents are NULL or not, otherwise you might be accessing an invalid pointer 您必须小心,但要检查内容是否为NULL,否则您可能正在访问无效指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM