【发布时间】:2013-11-16 14:52:50
【问题描述】:
小例子:
#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 中进行复制?
【问题讨论】:
-
@AlecTeal 你确定吗?我不期望复制省略,我的问题与省略构造函数/RVO 无关(编译器不能在这里做 RVO)。
-
不,但它会教你如何构造和东西,如果你有 "T t; t=otherT;"如果您说“T t = otherT;”,它将使用分配即使您写了“=”,它也不会默认构造和分配。如果它是一个 r 值,它会移动。
-
我不太明白您为什么会感到困惑,这种行为怎么会出乎意料?
-
顺便说一句,刚刚针对 Clang 3.4 和 G++ 4.8.2 测试了您的代码,结果相同
标签: c++ c++11 copy-constructor move-constructor