什么时候在堆栈上实例化C ++类? [英] When is a C++ class instantiated on the stack?

查看:59
本文介绍了什么时候在堆栈上实例化C ++类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想澄清一下在堆栈上实例化一个类时会发生什么.

I would like some clarification on what happens when a class is instantiated on the stack.

在堆上实例化C ++类时:

When a C++ class is instantiated on the heap:

MyClass *myclass = new MyClass();

创建类型为MyClass的指针,并通过"new MyClass();"在同一行上实例化该类.像这样拉伸它:

a pointer is created of type MyClass and the class is instantiated on the same line by "new MyClass();". Stretching it out like this:

MyClass *myclass;
myclass = new MyClass();

如果我没记错的话,会在第一行创建一个指针,然后在第二行为该实例分配内存,并将指向该实例地址的指针分配给myclass.

If I'm not mistaken, a pointer is created on the 1st line and then memory is allocated for the instance on the 2nd line and a pointer to the address of the instance is assigned to myclass.

这是否意味着当以这种方式在堆栈上实例化一个类时:

Does this mean that when a class is instantiated on the stack this way:

MyClass myclass = MyClass();

它被创建了两次?

推荐答案

在C ++中堆栈"和堆"没有定义,不需要在任何地方分配内存.

"Stack" and "heap" have no definition in C++, memory is not required to be allocated anywhere.

这里有您的示例:

MyClass myclass = MyClass();

您正在通过复制构造函数将 myclass 初始化到临时对象. myclass (和临时类)具有自动存储功能,如果您感到满意,可以考虑将其分配在堆栈"上.

You are initializing myclass via copy constructor to the temporary object. myclass (and the temporary) has automatic storage which you can consider being allocated on "the stack" if that makes you happy.

复制省略,从本质上将其优化为 MyClass myClass ,但是请注意,它不能总是这样做,例如当复制构造函数为private时.

Copy elision is allowed in this case, essentially optimizing it to MyClass myClass, however note that it cannot always do this, such as when the copy constructor is private.

以下是您可以测试的示例:

Here is an example that you can test:

struct obj {
  static int c;
  int myc;
  obj() : myc(c++) {
    std::cout << "ctor of " << myc << '\n';
  }
  obj(const obj&) : myc(c++){
    std::cout << "copy ctor of " << myc << '\n';
  }
  ~obj() {
    std::cout << "dtor of " << myc << '\n';
  }
};
int obj::c = 1;

int main(int argc, char** argv)
{
  obj x = obj();
}

如果删除副本,您将看到:

If the copy is elided you will see:

ctor of 1
dtor of 1

否则(gcc选项-fno-elide-constructors防止发生省略):

Otherwise (gcc option -fno-elide-constructors to prevent the elision happening):

ctor of 1
copy ctor of 2
dtor of 1
dtor of 2

此外,将复制构造函数设为私有将导致编译器错误.

Additionally, making the copy constructor private will give a compiler error.

这篇关于什么时候在堆栈上实例化C ++类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆