eer*_*ika 4 c++ rvalue-reference c++11
我有一个复杂的类类型,我想定义一个默认的常量实例,可以将其复制并用作函数的参数。我还想将该实例用作默认参数,以便可以在没有它的情况下调用该函数。该函数需要一个 const 右值引用。
在下面的代码中,函数test1的缺点是定义默认值的代码是重复的。
功能 test2 是否有效?第一次调用后,defaultS 会处于未指定状态吗?在这种情况下,有没有更好的方法来避免代码重复?
无论是否使用优化(gcc 4.8)编译时,代码都会按预期打印 2 1 1 。但是,可以依赖它与任何编译器(支持 c++11)一起工作吗?
#include <iostream>
#include <utility>
struct S {
// Imagine that this is a very complex class.
int data1, data2, data3;
};
// Duplicated code for defining default parameter and the constexpr.
// This example is trivial, but remember that S is more complex in a real use case.
constexpr S defaultS = {0, 0, 1};
void test1(const S&& arg = S{0, 0, 1}) {
std::cout << arg.data1 + arg.data2 + arg.data3 << std::endl;
}
// Default values are defined only once when defining defaultS.
// Will defaultS be unspecified after first call?
void test2(const S&& arg = std::move(defaultS)) {
std::cout << arg.data1 + arg.data2 + arg.data3 << std::endl;
}
int main(int argc, char **argv) {
// Use case for defaultS.
// Most values are default but a few are changed.
auto param = defaultS;
param.data3 = 2;
test1(std::move(param));
test2(); // defaultS is moved from.
test2(); // defaultS is used again here. Is it unspecified?
// and will there therefore be undefined behaviour?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
由于std::move(defaultS)将参数类型推导为 asS const&并返回 a typename std::remove_reference<S const&>::type&&,即 aS const&&我认为代码没问题:您将无法从S const&&对象原样移动const。
S const&&我认为,将 a作为论点没有多大意义。当您想将 aS&&作为参数时,您需要创建一个对象,例如使用
void foo(S&& value = S(defaultS)) { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
746 次 |
| 最近记录: |