最小的例子:
#include <iostream>
struct my_class
{
int i;
my_class() : i(0) { std::cout << "default" << std::endl; }
my_class(const my_class&) { std::cout << "copy" << std::endl; }
my_class(my_class&& other) { std::cout << "move" << std::endl; }
my_class(const my_class&& other) { std::cout << "move" << std::endl; }
};
my_class get(int c)
{
my_class m1;
my_class m2;
return (c == 1) ? m1 : m2; // A
//return (c == 1) ? std::move(m1) : m2; // B
//return (c == 1) ? m1 : std::move(m2); // C
}
int main()
{
bool c;
std::cin >> c;
my_class m = get(c);
std::cout << m.i << std::endl; // nvm about undefinedness
return 0;
}
编译:
g++ -std=c++11 -Wall -O3 ctor.cpp -o ctor # g++ v 4.7.1
输入:
1
输出:
default
default
copy
-1220217339
这是 A 行或 C 行的输入/输出。如果我使用 B 行,我会std::move
因为一些奇怪的原因而得到。在所有版本中,输出不依赖于我的输入(i 的值除外)。
我的问题:
- 为什么版本 B 和 C 不同?
- 为什么编译器会在案例 A 和 C 中进行复制?