I'm reading the answer to When should I use the new keyword in C++?, and Why should C++ programmers minimize use of 'new'?. but I'm a little bit confused.
Is it correct to say that I should use the new
keyword whenever I want to create an object whose size could change a lot?
Or do I use new
whenever I don't know the size of an object at compile-time?
Take the following examples:
A
std::vector
which I don't know the size of at compile time, containing user-defined objects. Once initialized, the size never changes.A
std::vector
which I know the initial size of, but whose size could change throughout the program.A user defined object containing
std::vector
objects, whose sizes all don't change. Other fields also don't change in size, but the sizes are not known at compile-time.A user defined object whose fields could all change in size
It seems to me that I should use new
in case 1 and 2, but not 3 and 4. Although, in 3 and 4, I should use new
to allocate memory for the fields inside the user defined object. Is this correct?
Does the usage of new
depend on how much the size of an object changes?
If I don't use new
, what risks am I taking (such as stackoverflow?)?
In examples 3 and 4, If I don't use new
, and I pass this object around, will I be making copies of the object each time I pass it?
If so, and the size of the object is "too big" (for instance, it has many, very large fields), could passing the object possibly cause a stackoverflow, corrupting the data of other objects on the stack?
Finally, when using new
, I understand I also have to use delete
. However, if a lot of different objects (let's call them A, B, and C) have access to the same pointer (P*), how does calling delete
in A affect P* in B and C? I assume it frees up the memory for all of them, such that if I now call P->get_something() in B or C, I would receive a segfault. Then, to prevent a memory leak, as long as something still has access to P*, I should not call delete
, but as soon as I'm sure nothing has access to P*, I need to delete it, right?