[英]Can I create a boost::shared_ptr to a local variable?
我有一些方法可以引用給定的對象,有些方法正在使用boost::shared_ptr
。 到目前為止,在我的測試方法中,我創建了一個指向其中一個對象的shared_ptr
,並將*ptr
傳遞給期望引用的方法。 是否有可能以相反的方式進行,例如在堆棧上創建一個本地對象,然后以安全的方式創建一個指向它的共享指針,以便用傳統指針直接替換&obj
運算符?
如果您發現需要這個,那么您的代碼可能會出現嚴重錯誤。
如果函數采用共享指針,那應該是因為它們需要延長對象的生命周期。 如果他們不需要延長對象的生命周期,他們應該參考。
通過你正在做的事情,他們無法延長對象的生命周期。 如果他們需要,也不能,他們可能會通過您傳遞的共享指針的副本來訪問超出范圍的對象。 繁榮。
這可能有點意義。 它們可能需要延長壽命,但是您將確保對象保持有效的時間長於它們可能需要延長的最長時間。 但我仍強烈建議不要這樣做。 它非常脆弱,使您調用的所有代碼完全依賴於調用代碼的行為方式。
#include <boost/shared_ptr.hpp>
void null_deleter(int *)
{}
int main()
{
int i = 0;
boost::shared_ptr<int> p(&i, &null_deleter);
}
您可以在表單的構造函數中傳遞適當的刪除器:
template<class Y, class D> shared_ptr(Y * p, D d);
deleter對象必須在其operator()()
不執行任何operator()()
,例如函數:
template <typename T>
void no_op(T*) {}
然后你可以用它構建:
boost::shared_ptr<Foo> f(&obj, no_op<Foo>);
你可以使用c ++ 11 lambda函數:
boost::shared_ptr<Foo> f(&obj, \[ ](Foo*){});
您可以在構造函數中傳遞null_deleter。
#include <boost/shared_ptr.hpp>
#include <boost/core/null_deleter.hpp>
int main()
{
int a = 0;
boost::shared_ptr<int> pi(&a, boost::null_deleter());
}
但請注意這種情況:破壞后使用對象:
#include <boost/shared_ptr.hpp>
#include <boost/core/null_deleter.hpp>
class Y
{
public:
void tryUse()
{
std::cout << "attempt to use :"<< (uintptr_t)(void*)this<< std::endl;
}
~Y()
{
std::cout << "destructor: "<< (uintptr_t)(void*)this<< std::endl;
}
};
struct Y_user
{
boost::shared_ptr<Y> p;
~Y_user()
{
std::cout << "Y_user destructor: "<< (uintptr_t)(void*)this<< std::endl;
if (p.get())
p->tryUse();
}
};
int main()
{
{
Y_user yu;
Y y;
boost::shared_ptr<Y> p (&y, boost::null_deleter() );
yu.p = p;
}
}
將導致控制台輸出如下:
destructor: 140737179995232
Y_user destructor: 140737179995264
attempt to use :140737179995232
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.