I created an array of simple Dummy objects on the stack:
Dummy a(8);
Dummy b(9);
Dummy dummies[2] = {a,b};
There is a MyObject object. I created it on the stack. The constructor stores this array into an instance variable.
class MyObject{
Dummy* _dummies;
MyObject obj(Dummy* dummies):
: _dummies(dummies)
{
}
};
MyObject obj(dummies);
When obj is removed and its destructor is called is the memory of _dummies freed? I understand that instance variables on stack are freed automatically, but how does MyObject know that this pointer points to an array on the stack and not to a Dummy object created on the heap?
In the constructor is the dummies array passed by value or reference? It is a pointer, but it is an array on the stack after all.
I understand stack, heap, passing by value and reference, but arrays on the stack handled with pointers really confuse me. I have always used vector, because it is clear and simple, but I would like to understand simple arrays too.
EDIT: thank you all. Now I understand that MyObject doesn't have anything to do with the array's lifetime. When dummies array is out of scope it gets removed.
BUT: what if "Dummy" is replaced with "char"? It is quite standard to have a char* on the stack (returned from a function for example), and pass it to an object, which then stores it simply by saving the pointer to the first char. Is that one a bad practice too? (I am going to use std::vector and std::string instead, much simpler...)