1

Actually I want to extract shared_ptr from 'this' object in an another function. For the same suppose we have a situation where a "Thing member function" needs to pass a pointer to "this" object to another function like:

#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();
}

output: Debug Assertion failed! Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

Am I doing any mistake which causing this run time exception ?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
peterDriscoll
  • 377
  • 4
  • 8
  • That error message suggests memory corruption to me. I do not see anything obviously wrong with your code and would suggest `valgrind`. – zwol Mar 29 '14 at 02:55
  • This is why I prefer using raw pointers over shared_ptr for function parameters. http://stackoverflow.com/a/142945/5987 – Mark Ransom Mar 29 '14 at 03:01

1 Answers1

4

You are causing a double-delete. That's because when you create a shared_ptr from this, you don't tell it that the raw pointer is already owned by someone else. You need to either use a custom, no-op deleter (construct shared_ptr with (this, [](void*){}), or use std::enable_shared_from_this.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436