Difference between revisions of "cpp/utility/move if noexcept"
m (Text replace - "/sidebar" to "/navbar") |
(grammar) |
||
Line 13: | Line 13: | ||
{{ddcl list end}} | {{ddcl list end}} | ||
− | + | {{tt|move_if_noexcept}} obtains an rvalue reference to its argument if its move constructor does not throw exceptions, otherwise obtains an lvalue reference to its argument. It is typically used to combine move semantics with strong exception guarantee. | |
− | For example, {{c|std::vector::resize | + | For example, {{c|std::vector::resize}} occasionally allocates new storage and then moves or copies elements from old storage to new storage. If an exception occurs during this operation, {{c|std::vector::resize}} undoes everything it did to this point, which is only possible if {{c|std::move_if_noexcept}} was used to decide whether to use move construction or copy construction. |
===Parameters=== | ===Parameters=== |
Revision as of 14:32, 2 July 2012
Template:ddcl list begin <tr class="t-dsc-header">
<td><utility>
<td></td> <td></td> </tr> <tr class="t-dcl ">
<td >typename std::conditional<
!std::is_nothrow_move_constructible<T>::value && std::is_copy_constructible<T>::value,
const T&,
T&&
<td class="t-dcl-nopad"> </td> <td > (since C++11) </td> </tr> Template:ddcl list end
move_if_noexcept
obtains an rvalue reference to its argument if its move constructor does not throw exceptions, otherwise obtains an lvalue reference to its argument. It is typically used to combine move semantics with strong exception guarantee.
For example, std::vector::resize occasionally allocates new storage and then moves or copies elements from old storage to new storage. If an exception occurs during this operation, 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 |
Parameters
x | - | the object to be moved or copied |
Return value
std::move(x) or x, depending on exception guarantees.
Exceptions
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
Complexity
Constant
See also
(C++11) |
forwards a function argument and use the type template argument to preserve its value category (function template) |
(C++11) |
converts the argument to an xvalue (function template) |