Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ delete an object

I am not experienced in handling of the memory in a C++ program, so I would like a piece of advice in that case:

I want to create a new Object in a function in a class which is essential till the end of the program. As far as I am concerned, if I use the operator new, I should sometimes delete it. Taking into account that it must be initialized inside a class, when and how must I finally delete it?

like image 951
arjacsoh Avatar asked Nov 29 '11 12:11

arjacsoh


1 Answers

I suggest the smart pointer idiom

#include <memory>

struct X 
{
     void foo() { }
};

std::share_ptr<X> makeX() // could also be a class member of course
{
    return std::make_shared<X>();
}

int main()
{
     std::share_ptr<X> stayaround = makeX();

     // can just be used like an ordinary pointer:

     stayaround->foo();

     // auto-deletes <sup>1</sup>
}

If the pointer is truly a static variable, you can substitute a unique_ptr (which works similarly, but passes ownership on assignment; this means that the pointer doesn't have to keep a reference count)

Note To learn more about C++ smart pointers in general, see   smart pointers (boost) explained  

Note If you don't have the TR1/C++0x support for this, you can just use Boost Smartpointer


1 unless you are leaking copies of the shared_ptr itself; that would be some strange use of smart pointers previously unseen :)

like image 197
sehe Avatar answered Sep 28 '22 09:09

sehe