문제

I have a function like this:

void cb( void *obj )
{
    if(nullptr != obj)
    {
        auto f = static_cast< function<void()>* >(obj);
        (*f)();
    }
}

and I use it this way:

auto obj = new function<void()> ( bind(&AClass::AMethod, &x) );
cb(obj);

where AClass is a class, AMethod is a method of AClass and x is an instance of AClass.

Now the question is: why deleting the pointer to std::function inside cb makes the program crash:

void cb( void *o )
{
    if(nullptr != o)
    {
        auto f = static_cast< function<void()>* >(o);
        (*f)();
        delete f; // <===
    }
}

whilst deleting it after the call to cb does not?

auto obj = new function<void()> ( bind(&AClass::AMethod, &x) );
cb(obj);
delete obj; // <===
도움이 되었습니까?

해결책

This works fine on both g++ 4.8.1 and clang 3.4. Also both show nothing of interest valgrind. So maybe the problem is somewhere else in your code or related to your compiler version?

I tested deleteing at both of the mentioned places.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top