簡體   English   中英

如何使用命名變量為const rvalue引用參數定義默認值?

[英]How to define default for a const rvalue reference parameter using a named variable?

我有一個復雜的類類型,我想定義一個默認的常量實例,該實例可以復制用作函數的參數。 我也想將該實例用作默認參數,以便在沒有該實例的情況下調用該函數。 該函數需要一個常量值引用。

在以下代碼中,函數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)將參數類型推導為S const&並返回類型名稱typename std::remove_reference<S const&>::type&& ,即S const&&我認為代碼是可以的:您不會可以從S const&&移動,因為對象是const

我認為以S const&&作為參數沒有太大意義。 當您想使用S&&作為參數時,您需要創建一個對象,例如使用

void foo(S&& value = S(defaultS)) { ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM