根据 OP 的要求,这是我的评论的改编版本
我实际上想知道同样的事情(特别是因为标准不“要求”复制省略)std::vector
,所以我通过替换Widget 结构在在线编译器中快速测试了它:
struct Widget
{
int val = 0;
Widget() { printf("default ctor\n"); }
Widget(const Widget&) { printf("copy ctor\n"); }
Widget(Widget&&) { printf("move ctor\n"); }
Widget& operator=(const Widget&) { printf("copy assign\n"); return *this; }
Widget& operator=(Widget&&) { printf("move assign\n"); return *this; }
~Widget() { printf("dtor\n"); }
void method(int)
{
printf("method\n");
}
};
V1 使用build_vector()
:http ://coliru.stacked-crooked.com/a/5e55efe46bfe32f5
#include <cstdio>
#include <array>
#include <cstdlib>
using std::array;
struct Widget
{
int val = 0;
Widget() { printf("default ctor\n"); }
Widget(const Widget&) { printf("copy ctor\n"); }
Widget(Widget&&) { printf("move ctor\n"); }
Widget& operator=(const Widget&) { printf("copy assign\n"); return *this; }
Widget& operator=(Widget&&) { printf("move assign\n"); return *this; }
~Widget() { printf("dtor\n"); }
void method(int)
{
printf("method\n");
}
};
bool some_condition(int x)
{
return (x % 2) == 0;
}
array<int, 3> something()
{
return {{1,2,3}};
}
Widget build_vector(int n)
{
if (some_condition(n)) return {};
Widget out;
for(int x : something())
{
out.method(x);
}
return out;
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
return -1;
}
const int x = atoi(argv[1]);
printf("call build_vector\n");
Widget w = build_vector(x);
printf("end of call\n");
return w.val;
}
V1的输出
call build_vector
default ctor
method
method
method
move ctor
dtor
end of call
dtor
V2 使用nrvo_friendly_build_vector()
:http ://coliru.stacked-crooked.com/a/51b036c66e993d62
#include <cstdio>
#include <array>
#include <cstdlib>
using std::array;
struct Widget
{
int val = 0;
Widget() { printf("default ctor\n"); }
Widget(const Widget&) { printf("copy ctor\n"); }
Widget(Widget&&) { printf("move ctor\n"); }
Widget& operator=(const Widget&) { printf("copy assign\n"); return *this; }
Widget& operator=(Widget&&) { printf("move assign\n"); return *this; }
~Widget() { printf("dtor\n"); }
void method(int)
{
printf("method\n");
}
};
bool some_condition(int x)
{
return (x % 2) == 0;
}
array<int, 3> something()
{
return {{1,2,3}};
}
Widget nrvo_friendly_build_vector(int n)
{
Widget out;
if (some_condition(n)) return out;
for(int x : something())
{
out.method(x);
}
return out;
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
return -1;
}
const int x = atoi(argv[1]);
printf("call nrvo_friendly_build_vector\n");
Widget w = nrvo_friendly_build_vector(x);
printf("end of call\n");
return w.val;
}
V2的输出
call nrvo_friendly_build_vector
default ctor
method
method
method
end of call
dtor
如您所见,在这种特殊情况下(some_condition 不会看到构造结构的副作用)some_condition()
,如果为 false ,V1 调用 move 构造函数(至少在 clang 和 gcc 中,在Coliru-std=c++11
中使用and )-O2
此外,正如您所注意到的,同样的行为似乎也发生了-O3
。
高温高压
ps:在学习复制省略时,您可能会发现Abseil 的 ToW #11很有趣;)