名稱空間
變體
操作

std::move_if_noexcept

來自 cppreference.com
< cpp‎ | 工具
 
 
 
在標頭檔案 <utility> 中定義
template< class T >
/* 參見下文 */ move_if_noexcept( T& x ) noexcept;
(C++11 起)
(C++14 起為 constexpr)

std::move_if_noexcept 獲取其引數的右值引用,當其移動建構函式不丟擲異常或沒有複製建構函式(僅可移動型別)時;否則,獲取其引數的左值引用。它通常用於將移動語義與強異常保證結合。

std::move_if_noexcept 的返回型別是

目錄

[編輯] 引數

x - 要移動或複製的物件

[編輯] 返回值

std::move(x)x,取決於異常保證。

[編輯] 複雜度

常數時間。

[編輯] 注意

這被 std::vector::resize 等使用,它可能需要分配新的儲存並從舊儲存移動或複製元素到新儲存。如果此操作期間發生異常,std::vector::resize 會撤銷它在此點所做的一切,這隻有在使用 std::move_if_noexcept 決定是使用移動構造還是複製構造時才可能(除非複製建構函式不可用,在這種情況下無論如何都使用移動建構函式,並且可能會放棄強異常保證)。

[編輯] 示例

#include <iostream>
#include <utility>
 
struct Bad
{
    Bad() {}
    Bad(Bad&&) // may throw
    {
        std::cout << "Throwing move constructor called\n";
    }
    Bad(const Bad&) // may throw as well
    {
        std::cout << "Throwing copy constructor called\n";
    }
};
 
struct Good
{
    Good() {}
    Good(Good&&) noexcept // will NOT throw
    {
        std::cout << "Non-throwing move constructor called\n";
    }
    Good(const Good&) noexcept // will NOT throw
    {
        std::cout << "Non-throwing copy constructor called\n";
    }
};
 
int main()
{
    Good g;
    Bad b;
    [[maybe_unused]] Good g2 = std::move_if_noexcept(g);
    [[maybe_unused]] Bad b2 = std::move_if_noexcept(b);
}

輸出

Non-throwing move constructor called
Throwing copy constructor called

[編輯] 另請參閱

(C++11)
轉發函式引數並使用型別模板引數來保留其值類別
(函式模板) [編輯]
(C++11)
將引數轉換為亡值
(函式模板) [編輯]