先上代码
class Base {
public:
int val = -1;
Base() {}
Base(int v) :val(v) {}
};
自定义的类型对象
using namespace std;
class Test {
public:
Base* base;
Test(const Test& other) {
cout << "copy-constructor called : This=" << this << ",other=" << &other << endl;
base = other.base;
}
Test(Test&& other) noexcept {
cout << "rvalue copy-constructor called : This=" << this << ",other=" << &other << ",base->val=" << other.base->val << endl;
base = other.base;
other.base = nullptr;
}
explicit Test(Base* b) : base(b) {
cout << "constructor called : This=" << this << ",base->val=" << base->val << endl;
}
~Test() {
cout << "destructor called : This=" << this << endl;
if (base != nullptr)delete base;
}
};
测试函数
Test func() {
int val = 2;
return val == 1 ? Test(new Base(1)) :
val == 2 ? Test(new Base(2)) :
val == 3 ? Test(new Base(3)) : Test(new Base(0));
}
int main()
{
func();
}
运行结果
constructor called : This=00F6F58C,base->val=2
rvalue copy-constructor called : This=00F6F5A4,other=00F6F58C,base->val=2
rvalue copy-constructor called : This=00F6F6D0,other=00F6F5A4,base->val=2
destructor called : This=00F6F5A4
destructor called : This=00F6F58C
destructor called : This=00F6F6D0
为什么调用了两次右值参数的拷贝构造函数?
编译器是msvc2019 用gcc测试则不会发生此问题
估计是编译器的原因。我运行你的代码,GCC一次都没有调用右值拷贝构造函数。我本来认为是调用了一次,GCC优化掉了