Answer the question
In order to leave comments, you need to log in
Is there a mechanism for checking the validity of pointers in C++?
Good day!
Is it possible somehow in C++ to check the pointer for the availability of the memory area it points to?
The situation is the following. There is a dll that defines the Delegate class, which is a representation of a function of some class (used for callbacks). Its constructor has the following signature:
template<typename T, typename ... Args>
explicit Delegate(T* owner, (T::*function), Args ... args);
class Foo
{
public:
void func() {}
};
Foo* f = new Foo;
Delegate d(f, &Foo::func);
d(); // вызовется f->func();
Foo* f = new Foo;
Delegate* d = new Delegate(f, &Foo::func);
delete f;
(*d)(); // здесь будет необработанное исключение
class A
{
public:
A() : delegate_(this, &A::funcA) {}
Delegate callback() const { return delegate_; }
void funcA() {}
private:
Delegate delegate_;
};
class B
{
public:
void setCallback(const Delegate& d)
{ delegate_ = d; }
void event()
{ delegate_(); }
private:
Delegate delegate_;
};
// -------------------------------------
A* classA = new A;
B* classB = new B;
classB->setCallback(classA->callback());
delete classA;
classB->event(); // печаль-беда
Answer the question
In order to leave comments, you need to log in
For debugging, there is such a thing as a debug heap . As far as I understand, in the release of an adequate option to check the validity of the pointer can not be. You can try to get around this somehow. For example, to receive a shared_ptr, which will hint to the user that it is not necessary to delete the object ahead of time.
What you want to do is not possible, and it is not necessary, if the user gave you a pointer and then freed it, then he himself is a fool and there is nothing to be done about it. The only thing I would advise you to use is shared_ptr, so that it would be easier for the user to keep track of the lifetime of his object. In principle, you can store weak_ptr and, when called, check whether it is rotten.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question