I’m an Objective-C programmer, and am recently starting C++, and I’ve stumbled into this question on my code’s organization:
std::list<char *> stuff = std::list<char *>();
thing *object = new thing(stuff);
Where stuff would be an object that I’d need for the lifetime of my class (that is, until it gets destructed), how to avoid losing it?
On Objective-C, I could simply call -retain on the constructor. On C++?
Do not use pointers when you don’t need them, and don’t use owning raw pointers (unless you have a very good reason for them).
Use automatic storage duration:
The constructor of
thingwould takestd::list<char>as its argument:If you do it this way, the destructor of
thingwill be called whenthinggoes out of scope, implicitly calling the destructor ofstuff. Many good C++ books explain this in great detail.Unlike Objective-C, and C++ uses RAII rather than reference counting. The basic rule is: use automatic storage duration when possible, avoid raw owning pointers, and don’t use
newunless you have a good reason for it.