我对此有点生疏。我试图弄清楚对象声明,值和引用,堆栈和堆到底发生了什么。我知道基础知识,但不确定以下示例:
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结构也在堆栈中?或者这不是你做的事情?
答案 0 :(得分:1)
让我以更精确的方式重新评论:
1)这会在堆栈上创建一个a
变量,并使用临时MyObject(1)
的值初始化它,该值在堆栈上创建为MyObject
调用MyObject::MyObject(1)
作为构造函数。编译器可以消除中间步骤。您只需MyObject a(1);
注意:=
不是作业
2)通过调用MyObject
在堆上创建MyObject::MyObject(2)
并返回指向它的指针,用于初始化b
指针。
忘记
malloc
和memset
:他们分配内存,但不要忘记内容 CONSTRUCT对象。你越早忘记它们,对你来说就越好 和其他任何人。
3)在堆上创建Myobject
并通过调用Myobkect::Myobject(3)
构造,然后取消引用new
返回的指针,并将结果值用于初始化c
复制。堆上创建的对象被遗忘了#34;在那里。 (内存泄漏:你没有机会进一步访问它)
4)对象c
被复制到c
的本地参数myFunc
中(实际上两个c
是两个不同的对象)将存在于堆栈中直到功能退出。