gpt4 book ai didi

c++ - 类构造函数匹配,为什么这里没有调用move构造函数?

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:30 26 4
gpt4 key购买 nike

最近在学习移动构造函数,遇到一个奇怪的问题。我有以下代码:

#include <iostream>

class a
{
public:
a() { printf("default\n"); }
a(const a& aa) { printf("const lr\n"); }
a(a& aa) { printf("lr\n"); }
a(a&& aa) { printf("rr\n"); }
a(const a&& aa) { printf("const rr\n"); }
};

a foo()
{
return a();
}

void func(a& a) {
printf("func lr\n");
}

void func(a&& aa) {
printf("func rr\n");
}

int main()
{
printf("a1: ");a a1;
printf("a2: ");a a2(a1);
printf("a3: ");a a3(std::move(a2));
printf("a4: ");a a4(foo());
printf("a5: ");a a5(std::move(foo()));

func(foo());
}

输出是:

a1: default
a2: lr
a3: rr
a4: default
a5: default
rr
default
func rr

除 a4 外,一切都很好。我希望 foo() 的返回类型是右值。我认为 func() 的调用终于证明了这一点。那么为什么在构造a4的时候move构造函数没有被调用呢?同时在构造a5时调用。

最佳答案

这可能是因为 copy_elision .

Under the following circumstances, the compilers are required to omit the copy- and move- construction of class object:

  1. In initialization, if the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object:

T x = T(T(T())); // only one call to default constructor of T, to initialize x

  1. In a function call, if the operand of a return statement is a prvalue and the return type of the function is the same as the type of that prvalue:

    T f() { return T{}; }
    T x = f(); // only one call to default constructor of T, to initialize x
    T* p = new T(f()); // only one call to default constructor of T, to initialize *p

你的情况属于第二种情况。

关于c++ - 类构造函数匹配,为什么这里没有调用move构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48762444/

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