使用 C++ 17,我们将有可能返回不可移动(包括不可复制)类型,例如std::mutex
,通过可以被认为是保证返回值优化 (RVO):通过简化值类别保证复制省略:
struct nocopy { nocopy(nocopy&) = delete; nocopy() = default; };
auto getRVO(){
return nocopy();
}
我们还将有结构化绑定,允许:
tuple<T1,T2,T3> f();
auto [x,y,z] = f();
或(这里也使用我对构造函数的特征模板参数推导的理解)
template<typename T1,typename T2,typename T3>
struct many {
T1 a;
T2 b;
T3 c;
};
// (Original questions missed 'many' on the next line. Thanks, T.C.)
auto f(){ return many{string(),5.7, false} };
auto [x,y,z] = f();
但是这些功能是否可以实现这样的功能?
auto get_ensured_rvo_str(){
return std::pair(std::string(),nocopy());
}
auto get_class_and_mutex(){
return many{SomeClass(),std::mutex(),std::string()};
}
int main(){
auto rvoStr = get_ensured_rvo_str().first;
auto [ mtx,sc,str ] = get_class_and_mutex();
}
我的想法是,要使其正常工作,它需要在形成std::tuple
or时保证聚合构造函数参数的 RVO many
,但不会将其命名为 RVO (NRVO),它具体未包含在 P0144R2 提案中吗?
旁注:P0144R2 特别提到只支持移动类型:
2.6 只移动类型
支持仅移动类型。例如:
struct S { int i; unique_ptr<widget> w; }; S f() { return {0, make_unique<widget>()}; } auto [ my_i, my_w ] = f();