c++11 - 如何使用右值调用复制构造函数

标签 c++11 copy-constructor move-semantics move-constructor copy-elision

MWE:

struct A {
    A() {std::cout << "constructor" << std::endl; }
    A(const A& a) {std::cout << "copy constructor" << std::endl; }
    A(A&& a) {std::cout << "move constructor" << std::endl; }
};

int main() {
    A a1{};
    A a2{ a1 };
    A a3{ A{} };
    A a4{ std::move(a3) };
    return 0;
}

输出:

constructor
copy constructor
constructor
move constructor
使用

fora2 复制省略,这是编译器的优化,一切似乎都很好。然而,当我注释掉 move 构造函数时,将调用复制构造函数来代替 move 构造函数。如何将右值转换为 const 左值引用? 输出:

constructor
copy constructor
constructor
copy constructor

程序在VS2017中编译。

最佳答案

来自 en.cppreference.com:

If both copy and move constructors are provided and no other constructors are viable, overload resolution selects the move constructor if the argument is an rvalue of the same type (an xvalue such as the result of std::move or a prvalue such as a nameless temporary (until C++17)), and selects the copy constructor if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes a reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable.

这清楚地表明右值可以绑定(bind)到 const 左值引用。

关于c++11 - 如何使用右值调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51166116/

相关文章:

c++ - 如何在创建字符串之前测量字符串的长度形成一个整数

c++ - c++11 中的多线程?

c++ - 如何使用 std::shared_ptr 实现缓存管理器?

c++ - 是否可以通过删除基类中的复制构造函数/运算符来使派生类不可复制?

c++ - move 语义 std::move 如何使用它

C++11 右值引用寻址

c++11 - 我应该怎么做才能将数据/值/对象添加到初始化列表,然后将其发送到构造函数?

c++ - 析构函数导致段错误

c++ - 这是好代码吗? (复制构造函数和赋值运算符)

C++ - 组合复制/move 运算符和构造函数