命名空间
变体
操作

std::move_if_noexcept

来自 cppreference.cn
< 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)
将参数转换为亡值
(函数模板) [编辑]