统一初始化与新操作员之间的区别

发布于 2025-02-02 02:00:56 字数 348 浏览 3 评论 0原文

假设我有以下类:

Class Foo {
public:
    int j;
    Foo(int i){
        j = i;
        std::cout << j << endl;
    };
}

我是C ++的新手,我对以下两个代码是否在内存分配中执行相同的活动感到困惑。我记得知道 new 动态分配内存,但我不确定第一个块。第一个街区也这样做吗?

Foo foo{2};
Foo *foo2;
foo2 = new Foo(2);

Let's assume that I have the following class:

Class Foo {
public:
    int j;
    Foo(int i){
        j = i;
        std::cout << j << endl;
    };
}

I am new to C++ and I'm confused about whether the following two blocks of code perform the same activity regarding memory allocation. I remember learning that new allocates memory dynamically but I am not sure about the first block. Is the first block doing the same?

Foo foo{2};
Foo *foo2;
foo2 = new Foo(2);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天冷不及心凉 2025-02-09 02:00:56

案例1

在这里我们考虑:

Foo foo{2}; //this will create an object of type `Foo` on the stack

上面的语句将使用转换构造函数 foo :: foo(int) foo的对象。 >。

情况2

在这里我们考虑:

Foo *foo2;           //creates a pointer of type `Foo*` on the stack
foo2 = new Foo(2);   //assign foo2 the pointer returned from new Foo(2)

首先,我们创建一个名为foo2 type foo*foo*的指针。请注意,截至目前,该指针是非初始化

接下来,当我们编写foo2 = new Foo(2);时发生以下情况:

  1. 由于new Foo(2)类型foo的对象是使用转换构造函数在堆上创建的foo :: foo(int)


  2. 接下来,返回到动态分配的对象的指针。

  3. 此返回的指针分配给左侧

    foo2


还请注意,代替将i分配给j在构造函数内,您可以在构造函数初始化器列表中初始化j,如下所示:

Class Foo {
public:
    int j;
//--------------vvvv--------------> initialize j in the member initializer list
    Foo(int i): j(i){
       
        std::cout << j << endl;
    };
}

Case 1

Here we consider:

Foo foo{2}; //this will create an object of type `Foo` on the stack

The above statement will create an object of type Foo on the stack using the converting constructor Foo::Foo(int).

Case 2

Here we consider:

Foo *foo2;           //creates a pointer of type `Foo*` on the stack
foo2 = new Foo(2);   //assign foo2 the pointer returned from new Foo(2)

Here first we create a pointer named foo2 of type Foo* on the stack. Note that as of now this pointer is uninitialized.

Next, when we write foo2 = new Foo(2); the following things happen:

  1. Due to new Foo(2) an object of type Foo is created on the heap using the converting constructor Foo::Foo(int).

  2. Next, a pointer to that dynamically allocated object is returned.

  3. This returned pointer is assigned to foo2 on the left hand side.


Note also that instead of assigning i to j inside the constructor you can instead initialize j in the constructor initializer list as shown below:

Class Foo {
public:
    int j;
//--------------vvvv--------------> initialize j in the member initializer list
    Foo(int i): j(i){
       
        std::cout << j << endl;
    };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文