mercredi 21 janvier 2015

Calling std::function object pointing to the method of deallocated object

Consider this code:



#include <iostream>
#include <functional>

using namespace std;
using namespace std::placeholders;

typedef function<void(const int&)> SomeFunc;

class X {
public:
X(string name):name_(name)
{ cout << "ctor " << name_ << endl; }

~X()
{
cout << "dtor " << name_ << endl;
name_ = "empty";
}

SomeFunc
getSomeFunc()
{ return bind(&X::someMethod, this, _1); }

private:
string name_;

void
someMethod(const int& a)
{
cout << name_ << " some method with " << a << endl;
}
};


int main()
{
SomeFunc f;

{
shared_ptr<X> x(new X("Object"));
f = x->getSomeFunc();
f(1);
}

f(2);

return 0;
}


Sometimes, output gives me this:



ctor Object
Object some method with 1
dtor Object
empty some method with 2


other times this:



ctor Object
Object some method with 1
dtor Object
some method with 2


In real world, it would most probably give me crashes once deallocated object tries to access it's attributes. So here is a question - as function does not guarantee holding a reference to the object which method it's pointing to, what is the best practice to avoid crashes when function is called after referenced object was already deallocated?


One of the solutions I might think of - maintain a special flag bool deallocated_ inside object and check it inside the method which might be called after deallocation. However, I suspect, it's not reliable either.


Aucun commentaire:

Enregistrer un commentaire