std:: move_if_noexcept
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
헤더 파일에 정의됨
<utility>
|
||
|
template
<
class
T
>
/* 아래 참조 */ move_if_noexcept ( T & x ) noexcept ; |
(C++11부터)
(C++14부터 constexpr) |
|
std::move_if_noexcept
는 이동 생성자가 예외를 던지지 않거나 복사 생성자가 없는 경우(이동 전용 타입) 인수에 대한 rvalue 참조를 얻고, 그렇지 않으면 인수에 대한 lvalue 참조를 얻습니다. 일반적으로 이동 의미론과 강력한 예외 보장을 결합하는 데 사용됩니다.
std::move_if_noexcept
의 반환 타입은:
- T && 만약 std:: is_nothrow_move_constructible < T > :: value || ! std:: is_copy_constructible < T > :: value 가 true 인 경우.
- 그렇지 않으면, const T & .
목차 |
매개변수
| 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)
|
함수 인자를 전달하며 템플릿 타입 인자를 사용하여 값 범주를 보존함
(function template) |
|
(C++11)
|
인자를 xvalue로 변환함
(function template) |