gpt4 book ai didi

c++ - 当我按值传递参数时对象被破坏了?

转载 作者:太空狗 更新时间:2023-10-29 20:34:03 26 4
gpt4 key购买 nike

给定以下代码:

#include <iostream>
using namespace std;
class A {
public:
A() {
}
A(const A& a) {
cout << "A copy ctor" << endl;
}
virtual ~A() {
cout << "A dtor" << endl;
}
virtual void type() const {
cout << "This is A" << endl;
}
};
class B: public A {
public:
virtual ~B() {
cout << "B dtor" << endl;
}
virtual void type() const {
cout << "This is B" << endl;
}
};
A f(A a) {
a.type();
return a;
}
const A& g(const A& a) {
a.type();
return a;
}
int main() {
A *pa = new B();
cout << "applying function f:" << endl;
f(*pa).type();
cout << "~~~ delete: ~~~" << endl;
delete pa;
return 0;
}

我得到以下输出:

applying function f:
A copy ctor
This is A
A copy ctor
This is A
A dtor
A dtor
~~~ delete: ~~~
B dtor
A dtor

但是我有点不明白。可以看出,虽然我们从 f 存在,但那里的对象并没有被破坏。为什么它没有被破坏? (毕竟,我们离开了函数的范围,所以它必须被销毁,不是吗?)

注意:我强调了有问题的行(我不明白为什么会按这个顺序发生)

我们转到函数 f,此时,我们调用复制 c'tor 并打印“A copy ctor”(Ok),之后,我们返回函数 f 并转到 type(),并且然后,它打印“This is A”,现在我们从函数 f 中退出,所以我们调用复制 c'tor,因此将打印“A copy ctor”,但是,现在,析构函数没有被调用(虽然我们逃离函数 f)..?

我以为输出会是下面的(根据上面的描述):

applying function f:
A copy ctor
This is A
A copy ctor (escape from type)
A dtor (escape from type)
This is A (at the main)
~~~ delete: ~~~
B dtor
A dtor

最佳答案

C++ 标准允许按值函数参数在函数范围内或调用范围内销毁。

如果在调用范围内,它会在完整表达式的末尾被销毁(通常是 ; )。如果在函数内部,则在构造返回值并销毁自动存储局部变量后销毁。

A *pa = new B();

A B已创建,带有 A子对象基础。

cout << "applying function f:" << endl;
f(*pa)//.type();

*pa 的切片拷贝作为 f 的参数创建.输出为 A copy ctor\n .

A f(A a) {
a.type();
return a;
}

A .type .在 A 的实例上调用.注意这个 A*pa 的拷贝, 但它只是 A 的拷贝*pa的一部分.

输出为 This is A , 其次是 A(A&&)移动 ctor,后跟可选的 A dtor .在你的情况下,你有一个复制 ctor 而不是移动 ctor,所以它被称为。不能省略此复制/移动,因为不允许从函数参数中省略。输出为 A copy ctor .

此时,编译器可以选择性地销毁 A这是 f 的论点.您的编译器不会破坏 f 的参数在这里。

f(*pa).type();

临时Af 返回现在有.type()在其上调用。这里没有多态性;方法 A::type()被直接调用。输出为 This is A .

然后我们到达了完整表达式的末尾。

现在由 f 返回的临时文件被销毁,然后是 f 的参数如果不是早点毁掉的话。所以输出是A dtor .

cout << "~~~ delete: ~~~" << endl;
delete pa;

B对象 *pa被销毁,然后回收内​​存。作为~A是虚拟的,调用适当的析构函数 *pa .

输出为 B dtor\nA dtor\n .

关于c++ - 当我按值传递参数时对象被破坏了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251557/

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