我有一个复杂的类类型,我想定义一个默认的常量实例,它可以被复制并用作函数的参数。我还想将该实例用作默认参数,这样就可以在没有它的情况下调用该函数。该函数需要一个 const 右值引用。
在下面的代码中,函数test1的缺点是定义默认值的代码重复了。
函数test2是否有效?第一次调用后 defaultS 会处于未指定状态吗?那么,是否有更好的方法来避免代码重复?
无论有无优化编译,代码都按预期打印 2 1 1 (gcc 4.8)。但是,是否可以依靠它与任何编译器(支持 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;
}
最佳答案
自 std::move(defaultS)
将参数类型推断为 S const&
并返回 typename std::remove_reference<S const&>::type&&
,即 S const&&
我认为代码没问题:您将无法从 S const&&
移动因为对象是 const
.
拿一个S const&&
意义不大作为论据,我想。当你想拍 S&&
作为参数,您需要创建一个对象,例如使用
void foo(S&& value = S(defaultS)) { ... }
关于c++ - 如何使用命名变量为 const 右值引用参数定义默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20778215/