【发布时间】:2016-01-27 15:35:10
【问题描述】:
考虑以下程序:
#include<iostream>
using namespace std;
struct S
{
S() = default;
S(const S& other) = delete;
S(S&& other) = delete;
int i;
};
S nakedBrace()
{
return {}; // no S constructed here?
}
S typedBrace()
{
return S{};
}
int main()
{
// produce an observable effect.
cout << nakedBrace().i << endl; // ok
cout << typedBrace().i << endl; // error: deleted move ctor
}
示例会话:
$ g++ -Wall -std=c++14 -o no-copy-ctor no-copy-ctor.cpp
no-copy-ctor.cpp: In function 'S typedBrace()':
no-copy-ctor.cpp:19:12: error: use of deleted function 'S::S(S&&)'
return S{};
^
no-copy-ctor.cpp:8:5: note: declared here
S(S&& other) = delete;
gcc 接受nakedBrace() 让我感到惊讶。我认为从概念上讲这两个函数是等效的:构造并返回一个临时的S。可能会或可能不会执行复制省略,但移动或复制 ctor(两者都在此处删除)必须仍然可以访问,如标准 (12.8/32) 所规定的那样。
这是否意味着nakedBrace() 从不构造 S?或者确实如此,但直接在带有大括号初始化的返回值中,因此在概念上不需要复制移动/ctor?
【问题讨论】:
标签: c++ temporary copy-elision