gpt4 book ai didi

c++ - 为什么在我的代码中调用复制构造函数而不是移动构造函数?

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

我试图理解移动构造函数和右值引用。所以我在 https://www.onlinegdb.com/online_c++_compiler 上尝试了这段代码.但结果让我感到困惑。

#include <iostream>
#include <type_traits>


class A {
public:
A() { std::cout << "Constructed" << std::endl; }
A(const A& )= delete;
A(A&&) { std::cout << "Move Constructed" << std::endl; }
};

int
main ()
{
A&& a = A();
A b = a; // error: use of deleted function ‘A::A(const A&)’
//A b = static_cast<decltype(a)>(a); // This works, WTF?
std::cout << std::is_rvalue_reference<decltype(a)>::value << std::endl; // pretty sure a is rvalue reference.

return 0;
}

最佳答案

您混淆了类型value categories .

(强调我的)

Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category.

作为命名变量,a是一个左值。

The following expressions are lvalue expressions:

  • the name of a variable, ...
  • ...

然后为 A b = a;复制构造函数被选中。如您所试,static_cast<decltype(a)>(a);会将其转换为 xvalue(右值);你也可以使用 std::move .

A b = std::move(a);

The following expressions are xvalue expressions:

  • a function call or an overloaded operator expression, whose return type is rvalue reference to object, such as std::move(x);
  • ...

关于c++ - 为什么在我的代码中调用复制构造函数而不是移动构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109156/

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