c++ - 将右值绑定(bind)到左值引用

标签 c++ constructor type-conversion copy-constructor

我有以下 C++ 代码(VS2013):

#include <iostream>
using namespace std;

class A {
    int i;
public:
    A(int i) : i(i) {
        cout << "Constructor: " << i << endl;
    }
    A(const A &o) : i(o.i) {
        cout << "Copy constructor: " << i << endl;
    }
    ~A() {
        cout << "Destructor: " << i << endl;
    }
};

A test(const A &a, A b, A *c) {
    return *c;
}

int main() {
    A b(10);
    cout << "START OF TEST" << endl;
    test(1, b, &b);
    cout << "END OF TEST" << endl;
    system("pause");
}

运行代码时,我在“START OF TEST”和“END OF TEST”输出之间得到以下输出:

Constructor: 1

Copy constructor: 10

Copy constructor: 10

Destructor: 10

Destructor: 10

Destructor: 1

构建了 3 个对象:1 个使用整数 1 , 和 2 使用类 A 的对象(我 = 10)。

值得一提的是,当 test函数的参数 const A &a更改为 A &a (不是常量),程序编译不通过,报错如下:

Error C2664: 'A test(A &,A,A *)' : cannot convert argument 1 from 'int' to 'A &'

如何解释这种行为?

具体来说:

  1. 为什么发送一个整数 1test制作A的参数构造函数A(int i)工作(并且仅当使用 const 时)?

  2. 为什么 A 的复制构造函数 A(const A &o) 工作了两次? (调用 test 时发生一次运行,返回 *c 时发生另一次运行)。

最佳答案

好吧,使用第一个参数 1 调用 test 会导致创建类型为 Arvalue。右值可以分配给 const lvalue reference 但不能分配给普通 lvalue 引用。如果您希望它在不使用 const 的情况下进行编译,您必须指定该参数是一个 rvalue 引用。

g++ 错误提供了更多信息:

 error: cannot bind non-const lvalue reference of type ‘A&’ to an rvalue of type ‘A’
     test(A(1), b, &b);

rvalue 可以分配给 rvalue referencelvalue reference to const

  • 这是为什么? 右值 是临时对象或文字。如果这段代码是合法的

    int &r = 5

    然后你就可以修改5了。 另一方面,对 const 的左值引用 禁止对它们引用的对象进行任何更改,因此您可以将它们绑定(bind)到 rvalue


const A& x = 1; //compile
x = 2;         //error!
A&& xxx = 1; //compile
A& xx  = 1; //does not compile.

关于第二个问题。您正在从 test 返回 A 的拷贝,因此 *c 触发了 c 拷贝的构造。 尝试从 test 返回引用 A 以查看未调用构造函数。

关于c++ - 将右值绑定(bind)到左值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44884560/

相关文章:

javascript - 从类静态方法调用 ES6 类构造函数

javascript - Douglas Crockford 的构造函数模式

c++ - 在构建时将对象存储在 vector 中

java - 重新转换 txt 文件(从 Windows 到 Unix)

c++ - 类型转换到另一个具有命名空间的类?

c++ - Boost::Python- 可以从 dict 自动转换 --> std::map?

c++ - 用模板实现替换预处理器 #ifdef block

C++预处理器

c++ - 如何在任务计划程序中显示所有任务

c++ - Visual Studio "go to header file"无法处理 hpp 文件