Tudor Tudor - 1 year ago 74
C++ Question

C++ structs and arrays on stack and heap, values, references, and dereferencing questions

I'm a bit rusty at this. I'm trying to figure out exactly what happens with object declaration, values and references, stack and heap. I know the basics, but am unsure about the following examples:

struct MyObject
int foo;
MyObject(int val)
foo = val;

MyObject()//[EDIT] default constructor


//this reserves memory on the stack for MyObject0 and initializes foo:
MyObject a = MyObject(1); //[EDIT] fixed from comments

MyObject* b = new MyObject(2);//This I know reserves memory on the heap,
//returns a pointer to it (and calls constructor).
//There are also other ways like malloc or memset.

MyObject c = *(new MyObject(3));// So here we instantiate MyObject on the heap,
//return a pointer to it but the pointer is dereferenced outside the parenthesis.
//Is c now a newly created value type copy on the stack?
//And is the original new MyObject(3) now inaccessible in the heap memory (leaked)
//because the pointer to it was never stored?

// void myFunc( MyObject c){}
myFunc(c); //Am I doing a member-wise assignment from c to a new function-scope
//temporary MyObject reserved somewhere else in memory (in a stack frame?)?
//Or am I somehow passing a reference to c even though c is not a pointer or reference?
//[EDIT] myFunc(c); would pass as a reference if I had void myFunc( MyObject &c){}

Finally, if I have a
MyObject[] myObjArr1 = new MyObject[10]()
I have 10 uninitialized MyObject structs on the heap, and a pointer of type
Array on the heap as well.

How do I declare a MyObject array, on the stack, where the MyObject structs within the array are also on the stack? Or is that not a thing you do?

Answer Source

Let me re-comment on a more precise way:

1) This creates an a variable on the stack initializing it with the value of the temporary MyObject(1), that is created on the stack as a MyObject calling MyObject::MyObject(1) as constructor. The compiler may eliminate the intermediate steps. You can do it simply as MyObject a(1); Note: the = is not an assignment

2) Creates a MyObject on heap by calling MyObject::MyObject(2) and returns a pointer to it, used initialize the b pointer.

Forget about malloc and memset: they allocate memory, but DON'T CONSTRUCT objects. The sooner you will forgot them, the better for you and anybody else.

3) a Myobject is created on the heap and constructed by calling Myobkect::Myobject(3), then The new returned pointer is dereferenced and the resulting value used to initialize c by copy. The on-heap created object is "forgotten" in there. (Memory leak: you have no chance to access it further)

4) The object c is copied in the local parameter c of myFunc (in fact the two c are two distinct objects) that will exist into the stack up to the function exit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download