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;
}
}
//...
//1)
//this reserves memory on the stack for MyObject and initializes foo:
MyObject a;//this defines a value type of a MyObject.
//Does it also call a default constructor here?
//Is it just an empty MyObject(){} that reserves memory for a MyObject?
a.foo = 1;//or is memory reserved only if you initialize something?
//2)
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.
//3)
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?
//4)
// 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?
Finally, if I have a MyObject[] myObjArr1 = new MyObject[10]
I have 10 uninitialized MyObject structs on the heap, and a pointer of type MyObject
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?
Aucun commentaire:
Enregistrer un commentaire