This question already has an answer here:
- std::shared_ptr of this 2 answers
I have the following code (this does not compile straight away as I would need a header and a cpp file to make up for circular dependencies but it gives all the information needed):
#include <memory>
#include <vector>
#include <iostream>
//////////////////////////////////
class MarchingEvent
{
public:
MarchingEvent() {}
void myFunction()
{
FunctionsHandler::myFunction(std::shared_ptr<MarchingEvent const>(this));
}
};
//////////////////////////////////
class FunctionsHandler
{
public:
static std::shared_ptr<MarchingEvent> myFunction( std::shared_ptr<MarchingEvent const> Ein )
{
// Do something in Ein.
return std::shared_ptr<MarchingEvent>();
}
}
//////////////////////////////////
int main()
{
std::shared_ptr<MarchingEvent> event = std:make_shared<MarchingEvent>();
// Some other code.
}
Now FunctionsHandler::myFunction() takes a shared pointer as argument, so I create a shared pointer out of this when calling the function in MarchingEvent::myFunction().
So it turns out there are 2 series of shared pointers following the same MarchingEvent object, because I create a 2nd shared pointer out of this. So obviously the MarchingEvent gets destroyed (and a crash occurs) when returning from FunctionsHandler::myFunction().
So how can I let this know about the shared pointer tracking it? So as not to create a 2nd one...
Aucun commentaire:
Enregistrer un commentaire