learning-notes icon indicating copy to clipboard operation
learning-notes copied to clipboard

在 gcc 中,如果函数返回临时对象,这个临时对象会被认为是右值(rvalue)吗?

Open daa233 opened this issue 8 years ago • 0 comments

#include <iostream>

using namespace std;

class Sample {
public:
    int v;
    Sample() {};
    Sample(int n) : v(n) {}
    Sample(Sample &x) {
        v = 2 + x.v;
    }
};

Sample PrintAndDouble(Sample o) {
    cout << o.v;
    o.v = 2 * o.v;
    return o;
}

int main() {
    Sample a(5);
    Sample b = a;
    // invalid initialization of non-const reference of type Sample from an rvalue of type Sample
    Sample c = PrintAndDouble(b);
    // const Sample &c = PrintAndDouble(b);
    cout << endl;
    cout << c.v << endl;
    Sample d;
    d = a;
    cout << d.v << endl;
}

上面这段代码,如果用 VC++ 编译不会报错,运行时会打印出

9
20
5

而如果用 gcc 编译,则会报出以下错误:

source_file.cpp: In function ‘int main()’:
source_file.cpp:25:30: error: invalid initialization of non-const reference of type ‘Sample&’ from an rvalue of type ‘Sample’
     Sample c = PrintAndDouble(b);
                              ^
source_file.cpp:10:5: note:   initializing argument 1 of ‘Sample::Sample(Sample&)’
     Sample(Sample &x) {

daa233 avatar Sep 28 '17 13:09 daa233