2014-03-29 14 views
1

其實我想提取從「此」對象的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)

我在做導致此運行時異常的任何錯誤嗎?

+0

這個錯誤信息給我帶來內存損壞,我沒有看到你的代碼有什麼明顯的錯誤,並且會提示'valgrind' 。 – zwol

+0

這就是爲什麼我更喜歡使用原始指針超過shared_ptr的函數參數。http://stackoverflow.com/a/142945/5987'的std :: enable_shared_from_this'的 –

回答

4

您正在導致雙重刪除。這是因爲當你從中創建一個shared_ptr時,你不會告訴它原始指針已經被其他人擁有。你需要使用一個自定義的無操作刪除器(使用(this, [](void*){})構造shared_ptr,或者使用std::enable_shared_from_this

+0

+1 – Sigismondo

相關問題