gpt4 book ai didi

c++ - 使用 'equal to' 符号初始化期间的内存

转载 作者:行者123 更新时间:2023-11-30 01:38:14 25 4
gpt4 key购买 nike

我试图了解在特定类型的初始化中使用的内存。这是问题的示例:

#include <iostream>
using namespace std;

class Example {
int n;
public:
Example(int number = 0)
{
n = number;
}
};

int main() {
Example *obj1 = new Example(1); //dynamic allocation - 1 instance is created and the object pointer points to the address
Example obj2(2); // automatic allocation - a single instance of the object is created with the given value
Example obj3 = Example(3); //automatic allocation - with copy constructor from an object initialized with a the class constructor

delete obj1; //de-allocating dynamically allocate memory
}

我很想知道 obj3 是如何被实例化的。使用等号是否意味着我们在这里使用了复制构造函数?如果是这样,Example(3) 是一个单独的实例吗(它的范围是什么)?

如果它们是单独的实例,那么似乎 obj2 的初始化更优化,不是吗?

编辑:修正了错误术语的使用——从静态到自动

最佳答案

I am interest in knowing how obj3 is being instantiated. Does the usage of the equals to sign mean that we are using a copy constructor here? If so, is Example(3) a separate instance (what is its scope)?

此表达式称为 copy initialization以及您在此处描述的 obj3 案例:

First, if T is a class type and the initializer is a prvalue expression whose cv-unqualified type is the same class as T, the initializer expression itself, rather than a temporary materialized from it, is used to initialize the destination object: see copy elision (since C++17)

因此,没有涉及复制构造函数,obj3 是针对当前标准直接初始化的(将 3 传递给它的构造函数)。在 C++17 临时文件可以创建之前,但很可能它会被优化器消除。

注意:您在注释中错误地指出自动变量使用静态内存分配。请在此处查看详细信息 Difference between static memory allocation and dynamic memory allocation

关于c++ - 使用 'equal to' 符号初始化期间的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48406726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com