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.
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<>
boost::shared_ptr<>
, , func(), , auto_ptr :
std::auto_ptr<Callback> p(new Callback); func(p.get());
, func() , .
/, . , , , . 0 -1, .
" ", (, ), ( , , delete , auto_ptr ..) , , , - , - , .
delete
auto_ptr
, ( ), " " ( ), - , , .
, auto_ptr, ", " (boost shared_ptr, ,...) - , ++ , , , ++ , , ( " " - , , ; -).
shared_ptr
, func() , Callback, , Callback, func(). , func(), , Callback . , , func() , , , .
, ++ , .
If your code is as simple as you wrote, and func()directly calls a callback at some point, this should be enough:
func()
Callback p; func(&p);
However, if you func()save the link or callback pointer elsewhere, you need to track the lifetime of that link.
Source: https://habr.com/ru/post/1710849/More articles:Why does UPPER () not work in MySQL? - mysqlEditing an XML file using JavaScript? - javascriptC # Bubbling / Walkthrough - c #How to make a flash movie to play full screen using javascript? - javascriptHow to set table column width for dynamic drop down list? - cssMinimize abbreviations in NSIS - installerNetwork Protocol Encapsulation - designUnstarring messages using the Google Reader API - pythonVisual Studio issues and compilation for a large number of files - performanceCombine task with TFS - tfsAll Articles