I'm relatively new to C++ (coming from Java) and I've got a little problem regarding lifetime of objects. My situation is like this: I'm having a class A in which I'm trying to add elements to an vector in class B. This vector itself shall hold objects (not pointers) of class C. However, since the objects are created in class As function, the are supposed to be deleted after the end of this function. So when I try to access these objects it gives me weird results. I'm currently passing the created objects as call by reference (using references instead of pointers). My question is, what can I do / use to have the vectors elements not deleted but saved for later use?
1 Answer
You need to use a smart pointer to own them. Which one you choose and how you manage their lifetime depends on your application. The most common one is unique_ptr
but there's also shared_ptr
and a couple others if you have a more specialist need.
Do not ever use new
and delete
to manage their lifetime. Only use new
if you have to implement make_unique
- otherwise never use it. Never use new[]
, delete
, delete[]
, or any strategy that requires them.
-
Thanks for your answer, exactly what I was looking for. I'm going to try it out now. Commented Feb 28, 2015 at 12:31