代码清单 3-30

#include <iostream>
using namespace std;
struct Copyable {
    Copyable() {}
    Copyable(const Copyable &o) { cout << "Copied" << endl; }
};
Copyable ReturnRvalue() { return Copyable(); }
void AcceptVal(Copyable) {}
void AcceptRef(const Copyable &) {}
int main() {
    cout << "Pass by value: " << endl;
    AcceptVal(ReturnRvalue()); // 临时值被拷贝传入
    cout << "Pass by reference: " << endl;
    AcceptRef(ReturnRvalue()); // 临时值被作为引用传递
}
// 编译选项:g++ 3-3-5.cpp -fno-elide-constructors

因为现在的编译器都很新了,而且现在 C++ 标准都更新到 c++26 了。所以,编译选项还要加一个 -std=c++11

这里要理解一下它的输出,

Pass by value: 
Copied
Copied
Pass by reference: 
Copied

为什么上面是拷贝了两次,而下面只拷贝了一次。

下面再来一点变化,

#include <iostream>
using namespace std;
struct Copyable {
    Copyable() {}
    Copyable(const Copyable &o) { cout << "Copied" << endl; }

    ~Copyable() { cout << "Destructed" << endl; }
};

Copyable ReturnRvalue() { return Copyable(); }
void AcceptVal(Copyable) {}
void AcceptRef(const Copyable &) {}

int main() {
    cout << "Pass by value: " << endl;
    AcceptVal(ReturnRvalue()); // 临时值被拷贝传入
    cout << "===================" << endl;
    cout << "Pass by reference: " << endl;
    AcceptRef(ReturnRvalue()); // 临时值被作为引用传递
    cout << "===================" << endl;
    cout << "before exit main." << endl;
}
// 编译选项:g++ 3-3-5.cpp -fno-elide-constructors -std=c++11
// output
/*
Pass by value: 
Copied
Destructed
Copied
Destructed
Destructed
===================
Pass by reference: 
Copied
Destructed
Destructed
===================
before exit main.
*/
#include <iostream>
using namespace std;
struct Copyable {
    Copyable() {}
    Copyable(const Copyable &o) { cout << "Copied" << endl; }

    ~Copyable() { cout << "Destructed" << endl; }
};

Copyable ReturnRvalue() { return Copyable(); }
void AcceptVal(Copyable) {}
void AcceptRef(const Copyable &) {}

int main() {
    cout << "Pass by value: " << endl;
    Copyable lval = ReturnRvalue();
    cout << "===================" << endl;
    cout << "Pass by reference: " << endl;
    const Copyable &rval = ReturnRvalue();
    cout << "===================" << endl;
    cout << "before exit main." << endl;
}
// 编译选项:g++ 3-3-5.cpp -fno-elide-constructors -std=c++11
// output
/*
Pass by value: 
Copied
Destructed
Copied
Destructed
Destructed
===================
Pass by reference: 
Copied
Destructed
Destructed
===================
before exit main.
*/

虽然这里说 const Copyable & 和 Copyable && 是等价的,但是,还是分不清。(fany存疑)