考虑以下:
struct A { /* ... */ };
A foo() {
auto p = std::make_pair(A{}, 2);
// ... do something
return p.first;
}
auto a = foo();
Run Code Online (Sandbox Code Playgroud)
会p.first被复制,移动还是RVO-ed?
鉴于此代码示例,有关传递给临时字符串的生命周期的规则是什么S.
struct S
{
// [1] S(const std::string& str) : str_{str} {}
// [2] S(S&& other) : str_{std::move(other).str} {}
const std::string& str_;
};
S a{"foo"}; // direct-initialization
auto b = S{"bar"}; // copy-initialization with rvalue
std::string foobar{"foobar"};
auto c = S{foobar}; // copy-initialization with lvalue
const std::string& baz = "baz";
auto d = S{baz}; // copy-initialization with lvalue-ref to temporary
Run Code Online (Sandbox Code Playgroud)
根据标准:
N4140 12.2 p5.1(在N4296中删除)
绑定到构造函数的ctor-initializer(12.6.2)中的引用成员的临时绑定将持续存在,直到构造函数退出.
N4296 12.6.2 p8
绑定到mem-initializer中的引用成员的临时表达式是错误的.
因此,拥有用户定义的构造函数[1]绝对不是我们想要的.它甚至应该在最新的C++ 14中形成不良(或者是它?)gcc和clang都没有警告它.
它是否随直接聚合初始化而改变?在这种情况下,我看起来,临时寿命延长了.
现在关于复制初始化,默认移动构造函数和引用成员状态[2] …