首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::move_if_noexcept

Defined in header <utility>

?

?

template< class T > typename std::conditional< !std::is_nothrow_move_constructible<T>::value && std::is_copy_constructible<T>::value, const T&, T&& >::type move_if_noexcept(T& x);

?

(since C++11) (until C++14)

template< class T > constexpr typename std::conditional< !std::is_nothrow_move_constructible<T>::value && std::is_copy_constructible<T>::value, const T&, T&& >::type move_if_noexcept(T& x);

?

(since C++14)

move_if_noexcept如果其移动构造函数不抛出异常,则获取对其参数的rvalue引用,否则将获得对其参数的lvalue引用。它通常用于将移动语义与强异常保证相结合。

参数

x

-

the object to be moved or copied

返回值

std::move(x)x,取决于例外担保。

例外

noexcept规格:

noexcept

注记

例如,这是由std::vector::resize,它可能必须分配新存储,然后将元素从旧存储移动或复制到新存储。如果在此操作期间发生异常,std::vector::resize取消它在这一点上所做的一切,这只有在以下情况下才有可能std::move_if_noexcept用于决定是使用移动构造还是复制构造。%28除非没有副本构造函数可用,否则使用移动构造函数,强异常保证可能放弃%29。

二次

代码语言:javascript
复制
#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;
    Good g2 = std::move_if_noexcept(g);
    Bad b2 = std::move_if_noexcept(b);
}

二次

产出:

二次

代码语言:javascript
复制
Non-throwing move constructor called
Throwing copy constructor called

二次

复杂性

常量。

另见

forward (C++11)

forwards a function argument (function template)

move (C++11)

obtains an rvalue reference (function template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com