variant_bad_variant_access

variant_bad_variant_access (bad_variant_access 예외)

std::bad_variant_accessstd::variant에 잘못된 방식으로 접근할 때 던져지는 예외 타입이에요. <variant> 헤더에 정의되어 있으며 C++17부터 사용할 수 있어요. 주로 std::get으로 현재 활성화된 대안과 일치하지 않는 인덱스나 타입을 요청하거나, std::visit로 값을 잃은 variant를 방문하려 할 때 발생해요.

출처: cppreference

본문

개요

<variant> 헤더에 정의됨
class bad_variant_access : public std :: exception (C++17부터)

std::bad_variant_access는 다음 상황에서 던져지는 예외의 타입이에요.

  • std::get (std::variant)를 현재 활성화된 대안(alternative)과 일치하지 않는 인덱스나 타입으로 호출한 경우
  • std::visit를 호출하여 valueless_by_exception 상태인 variant를 방문하려 한 경우
std::variant::visit를 호출하여 valueless_by_exception 상태인 variant를 방문하려 한 경우 (C++26부터)

멤버 함수

(constructor) 새로운 bad_variant_access 객체를 생성해요 (공개 멤버 함수)
operator= bad_variant_access 객체를 교체해요 (공개 멤버 함수)
what 설명 문자열을 반환해요 (공개 멤버 함수)

std::bad_variant_access::bad_variant_access

bad_variant_access () noexcept ; (1) (C++17부터)
bad_variant_access ( const bad_variant_access & other ) noexcept ; (2) (C++17부터)

구현에서 정의한 null 종료 바이트 문자열로 새 bad_variant_access 객체를 생성해요. 이 문자열은 what()을 통해 접근할 수 있어요.

매개변수

other - 복사할 다른 예외 객체

std::bad_variant_access::operator=

bad_variant_access & operator = ( const bad_variant_access & other ) noexcept ; (C++17부터)

other의 내용으로 내용을 할당해요. *thisother가 모두 동적 타입이 std::bad_variant_access라면, 할당 후 std :: strcmp ( what (), other . what ()) == 0이 성립해요.

매개변수

other - 할당에 사용할 다른 예외 객체

반환값

*this

std::bad_variant_access::what

virtual const char * what () const noexcept ; (C++17부터)

설명 문자열을 반환해요.

반환값

설명 정보가 담긴 구현 정의 null 종료 문자열에 대한 포인터예요. 이 문자열은 std::wstring으로 변환 및 표시하기에 적합해요. 포인터는 얻은 예외 객체가 소멸될 때까지, 또는 예외 객체에 대해 비-const 멤버 함수(예: 복사 대입 연산자)가 호출될 때까지 유효함이 보장돼요.

반환된 문자열은 상수 평가(constant evaluation) 중에 일반 리터럴 인코딩으로 인코딩돼요. (C++26부터)

참고

구현은 what()을 재정의할 수 있지만 필수는 아니에요.

std::exception에서 상속받은 멤버

멤버 함수

(destructor) [virtual] 예외 객체를 소멸해요 (std::exception의 가상 공개 멤버 함수)
what [virtual] 설명 문자열을 반환해요 (std::exception의 가상 공개 멤버 함수)

예제

#include <iostream>
#include <variant>

int main()
{
    std::variant<int, float> v;
    v = 12;
    try
    {
        std::get<float>(v);
    }
    catch (const std::bad_variant_access& e)
    {
        std::cout << e.what() << '\n';
    }
}

가능한 출력:

bad_variant_access

관련 항목

get (std::variant) (C++17) 인덱스나 타입이 주어졌을 때 variant의 값을 읽어요 (타입이 유일한 경우), 오류 시 예외를 던져요 (함수 템플릿)
visit (C++17) 하나 이상의 variant가 보유한 인수로 제공된 펑터(functor)를 호출해요 (함수 템플릿)
visit (C++26) variant가 보유한 인수로 제공된 펑터를 호출해요 (공개 멤버 함수)

더 알아보기 (Learn more)

cppreference