命名空间
变体
操作

std::move_if_noexcept

来自 cppreference.cn
< cpp‎ | utility
 
 
 
定义于头文件 <utility>
template< class T >
/* 见下文 */ move_if_noexcept( T& x ) noexcept;
(since C++11)
(constexpr since C++14)

`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)
将参数转换为 xvalue
(函数模板) [编辑]