When do you need to delete an object?

Callback* p = new Callback;
function(p);

If I want to delete a callback object, when and how to delete it?

If it is deleted earlier, then the callback may fail with a segmentation error.

+3
source share
6 answers

The best solution for this is to use a smart pointer.
You initialize the pointer with a callback and pass it to the function. when a function or any process is executed, the callback will be automatically deleted using the smart pointer.
Efficient smart pointer implementationboost::shared_ptr<>

+17
source

, , func(), , auto_ptr :

std::auto_ptr<Callback> p(new Callback);
func(p.get());

, func() , .

+3

/, . , , , . 0 -1, .

+1

" ", (, ), ( , , delete , auto_ptr ..) , , , - , - , .

, ( ), " " ( ), - , , .

, auto_ptr, ", " (boost shared_ptr, ,...) - , ++ , , , ++ , , ( " " - , , ; -).

+1

, func() , Callback, , Callback, func(). , func(), , Callback . , , func() , , , .

, ++ , .

+1

If your code is as simple as you wrote, and func()directly calls a callback at some point, this should be enough:

Callback p;
func(&p);

However, if you func()save the link or callback pointer elsewhere, you need to track the lifetime of that link.

+1
source

Source: https://habr.com/ru/post/1710849/


All Articles