其實我想提取從「此」對象的shared_ptr在另一個函數。 出於同樣假設我們有這樣一種情況:「事情成員函數」需要一個指向「這個」對象傳遞給另一個函數,如:爲「本」對象到另一個函數獲取shared_ptr的:讓運行時異常
#include "stdafx.h"
#include<memory>
using namespace std;
class Thing {
public:
void foo();
void defrangulate();
};
void Thing::defrangulate()
{
}
void transformIt(shared_ptr<Thing> ptr)
{
ptr->defrangulate();
/* etc. */
}
void Thing::foo()
{
// we need to transformIt this object
shared_ptr<Thing> sp_for_this(this);
transformIt(sp_for_this);
}
int main()
{
shared_ptr<Thing> t1(new Thing);// start a manager object for the Thing
t1->foo();
}
輸出: 調試斷言失敗! 表達式:_BLOCK_TYPE_IS_VALID(pHead-> nBlockUse)
我在做導致此運行時異常的任何錯誤嗎?
這個錯誤信息給我帶來內存損壞,我沒有看到你的代碼有什麼明顯的錯誤,並且會提示'valgrind' 。 – zwol
這就是爲什麼我更喜歡使用原始指針超過shared_ptr的函數參數。http://stackoverflow.com/a/142945/5987'的std :: enable_shared_from_this'的 –