我可以使用新的placement来重置shared_ptr中的对象吗? [英] Can I use placement new to reset an object within a shared_ptr?
问题描述
假设我有一个类。
class BigData {...};
typedef boost :: shared_ptr< BigData> BigDataPtr;
然后我:
BigDataPtr bigDataPtr(new BigData());
稍后我完成我的对象后,我确定没有其他用户的对象。
可以安全地执行以下操作:
bigDataPtr-> ;〜BigDataPtr();
new(& * bigDataPtr)BigData;这是否允许我重置对象而不进行任何额外的分配? div class =h2_lin>解决方案
是的,通常是安全的。 (点击Maxim Yegorushkin关于投掷边缘情况的观察结果)
请注意下面的拼写错误
Boost定义取消引用,并将 - >
运算符定义为
模板< class T>
typename boost :: detail :: sp_dereference< T> :: type boost :: shared_ptr& T> :: operator *()const;
template< class T>
typename boost :: detail :: sp_member_access< T> :: type boost :: shared_ptr& T> :: operator-> ()const;
当这些 detail
有这个
模板< class T>
T& boost :: shared_ptr< T> :: operator *()const
template< class T>
T * boost :: shared_ptr< T> :: operator-> ()const
所以你直接处理指向的对象。没有可能干扰您尝试的代理或其他结构。
指向数据时,您的代码:
bigDataPtr->〜BigDataPtr();
new(& * bigDataPtr)BigData;
可能有错字。但是如果您打算:
bigDataPtr->〜BigData
new(& * bigDataPtr)BigData;
将解析为
(BigData pointer) - >〜BigData();
new(&(BigData reference))BigData;
这是合法的,你是正确的,它会避免作业通常发生的额外分配。
Let's say I have a class.
class BigData {...};
typedef boost::shared_ptr<BigData> BigDataPtr;
Then I do:
BigDataPtr bigDataPtr(new BigData());
Later on after I am done with my object and I am sure there no other users for the object.
Is it safe to do the following:
bigDataPtr->~BigDataPtr();
new (&*bigDataPtr) BigData;
Would this let me reset the object without any additional allocations?
Yes it is normally safe. (Nod to Maxim Yegorushkin's observation about a throwing edge case)
Note the typo message below
Boost defines the dereference and ->
operators as
template<class T>
typename boost::detail::sp_dereference< T >::type boost::shared_ptr< T >::operator* () const;
template<class T>
typename boost::detail::sp_member_access< T >::type boost::shared_ptr< T >::operator-> () const;
When those detail
bits are resolved, you have this
template<class T>
T & boost::shared_ptr< T >::operator* () const
template<class T>
T * boost::shared_ptr< T >::operator-> () const
So you are dealing with the pointed-to object directly. There are no proxies or other constructs that may interfere with what you're attempting.
As the pointed-to data is concerned, your code:
bigDataPtr->~BigDataPtr();
new (&*bigDataPtr) BigData;
May have a typo. But if you intended:
bigDataPtr->~BigData();
new (&*bigDataPtr) BigData;
It will resolve to
(BigData pointer)->~BigData();
new (&(BigData reference)) BigData;
This is legal, and you are correct that it would avoid the additional allocation normally incurred with an assignment.
这篇关于我可以使用新的placement来重置shared_ptr中的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!