std::move_if_noexcept
From Cppreference
C++ Standard Library | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Utilities library | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Defined in header <utility>
|
||
template< class T >
typename std::conditional< |
(C++11 feature) | |
Obtains an rvalue reference to its argument if its move constructor does not throw exceptions, otherwise obtains an lvalue reference to its argument. Typically used to combine move semantics with strong exception guarantee.
For example, std::vector::resize() allocates new storage, and then moves or copies elements from old storage to new storage. If an exception occurs during this, std::vector::resize() undoes everything it did to this point, which is only possible if std::move_if_noexcept was used to decide whether to use move construction or copy construction.
Contents |
[edit] Parameters
x | - | the object to be moved or copied |
[edit] Return value
std::move(x)
[edit] Exceptions
[edit] Example
#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&) {}; }; int main() { Good g; Bad b; Good g2 = std::move_if_noexcept(g); Bad b2 = std::move_if_noexcept(b); }
Output:
Non-throwing move constructor called Throwing copy constructor called
[edit] Complexity
Constant
[edit] See also
|
forwards a function argument (function template) |
||
|
obtains an rvalue reference (function template) |