堆栈和堆上的C ++结构和数组,值,引用和解引用问题

时间:2016-11-27 14:43:55

标签: c++ c++11

我对此有点生疏。我试图弄清楚对象声明,值和引用,堆栈和堆到底发生了什么。我知道基础知识,但不确定以下示例:

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

    MyObject()//[EDIT] default constructor
    {
    }
}

//...

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

//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?
//[EDIT] myFunc(c); would pass as a reference if I had void myFunc( MyObject &c){}

最后,如果我有一个MyObject[] myObjArr1 = new MyObject[10]()我在堆上有10个未初始化的MyObject结构,并且堆上还有一个类型为MyObject Array的指针。

如何在堆栈上声明MyObject数组,其中数组中的MyObject结构也在堆栈中?或者这不是你做的事情?

1 个答案:

答案 0 :(得分:1)

让我以更精确的方式重新评论:

1)这会在堆栈上创建一个a变量,并使用临时MyObject(1)的值初始化它,该值在堆栈上创建为MyObject调用MyObject::MyObject(1)作为构造函数。编译器可以消除中间步骤。您只需MyObject a(1);注意:=不是作业

2)通过调用MyObject在堆上创建MyObject::MyObject(2)并返回指向它的指针,用于初始化b指针。

  

忘记mallocmemset:他们分配内存,但不要忘记内容   CONSTRUCT对象。你越早忘记它们,对你来说就越好   和其他任何人。

3)在堆上创建Myobject并通过调用Myobkect::Myobject(3)构造,然后取消引用new返回的指针,并将结果值用于初始化c复制。堆上创建的对象被遗忘了#34;在那里。 (内存泄漏:你没有机会进一步访问它)

4)对象c被复制到c的本地参数myFunc中(实际上两个c是两个不同的对象)将存在于堆栈中直到功能退出。