gpt4 book ai didi

c++ - 按值返回的函数无法按预期工作

转载 作者:搜寻专家 更新时间:2023-10-31 01:24:22 24 4
gpt4 key购买 nike

我是 C++ 新手。我了解到函数可以按值返回,但在我的代码中它似乎无法正常工作。

#include "pch.h"
#include <iostream>

class B {
public:
int* ip;
B() : ip(new int(0)) {}
//COPY CTOR
B(B& other){
ip = new int(0);
*ip = *other.ip;

}
//MOVE CTOR
B(B&& other) : ip(NULL){
ip = other.ip;
}
B& operator=(B& other)
{
int* ptr = new int(0);
*ptr = *other.ip;
delete ip;
ip = ptr;
}
B& operator=(B&& other)
{
int* ptr = new int(0);
*ptr = std::move(*other.ip);
delete ip;
ip = ptr;
}
~B() {
delete ip;
ip = NULL;
}
};

B CreateB()
{
B b;
*(b.ip) = 99;
return b;
}
int main()
{
B BObj(CreateB());
std::cout << "B.ip=" << *BObj.ip << std::endl;
system("pause");
return 0;
}

我在 Debug模式下使用 visual studio 2019,我介入了 CreateB() 并发现创建了本地对象 B。在“返回 b;”语句调试步进到 Move Constructor B(B&& other) 我发现这是编译器优化。编译器没有使用 Copy 构造函数从本地 B 对象创建 B 对象,而是使用了 Move Constructor。但是,在执行 Move 构造函数后,调试将我带到了析构函数 ~B()。现在函数返回给 main 的对象不见​​了。为什么编译器不使用 Copy Ctor 然后删除本地对象?谢谢!

最佳答案

Why didn't the compiler use Copy Ctor then deleted the local object?

因为,如您所见,它使用了移动构造函数。移动构造函数被调用,然后本地对象被销毁。 (当对象超出范围时调用析构函数,即使该对象已被移出。)

当本地对象被销毁时,它的ip成员指向的东西被删除了。这通常很好,只是移动的对象指向同一事物。您可能想让移动构造函数将 other.ip 设置为某个有效值。 (我通常建议使用 nullptr,但看起来您的类假定 ip 永远不会为 null。)

例如:

B(B&& other) : ip(other.ip){
other.ip = new int(0);
}

关于c++ - 按值返回的函数无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58194220/

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