我有一个复杂的类类型,我想定义一个默认的常量实例,该实例可以复制用作函数的参数。我还想将该实例用作默认参数,以便在没有该实例的情况下可以调用该函数。该函数需要一个常量值引用。
在以下代码中,函数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;
}
由于std::move(defaultS)
推导参数类型为asS const&
并返回a typename std::remove_reference<S const&>::type&&
,即a,S const&&
我认为代码是可以的:您将无法从S const&&
as对象移出const
。
S const&&
我认为,将其作为论点没有多大意义。当您想使用S&&
as参数时,您需要创建一个对象,例如使用
void foo(S&& value = S(defaultS)) { ... }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句