统一初始化与新操作员之间的区别
假设我有以下类:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
案例1
在这里我们考虑:
上面的语句将使用转换构造函数
foo :: foo(int) foo
的对象。 >。情况2
在这里我们考虑:
首先,我们创建一个名为
foo2
typefoo*foo*
的指针。请注意,截至目前,该指针是非初始化。接下来,当我们编写
foo2 = new Foo(2);
时发生以下情况:由于
new Foo(2)
类型foo的对象
是使用转换构造函数在堆上创建的foo :: foo(int)
。接下来,返回到动态分配的对象的指针。
此返回的指针分配给左侧
的
foo2
。还请注意,代替将
i
分配给j
在构造函数内,您可以在构造函数初始化器列表中初始化j
,如下所示:Case 1
Here we consider:
The above statement will create an object of type
Foo
on the stack using the converting constructorFoo::Foo(int)
.Case 2
Here we consider:
Here first we create a pointer named
foo2
of typeFoo*
on the stack. Note that as of now this pointer is uninitialized.Next, when we write
foo2 = new Foo(2);
the following things happen:Due to
new Foo(2)
an object of typeFoo
is created on the heap using the converting constructorFoo::Foo(int)
.Next, a pointer to that dynamically allocated object is returned.
This returned pointer is assigned to
foo2
on the left hand side.Note also that instead of assigning
i
toj
inside the constructor you can instead initializej
in the constructor initializer list as shown below: