C++/기타

[C++ keyword] explicit 란?

sseram 2023. 2. 25. 21:59
반응형

 

1. copy initialization을 막아주는 keyword.

    해당 keyword를 붙이면 direct initialization만 가능하다.

2. 암시적 형변환을 막아주는 keyword.

 

 

 

 

그래서 그게 머임?

 

쉽게 표현하자면,

copy initialization  : = 뒤에  나오는 표현 식에 의해 초기화 될 때

direct initialization   : (). {} 등으로 직접 초기화 될 때.

 

 

-> 밑의 예시를 보자.

struct A
{
	A(int) { }     
	A(int, int) { }
};

struct B
{
	explicit B(int) { }
	explicit B(int, int) { }
};

 

 

이런 식으로 explict를 쓰지 않은 A

explict 를 쓴 B가 있다고 하자.

 

저 두 개의 A, B를 다양한 방법으로 초기화 해 보았다.

	A a1 = 1;
	B b1 = 1;		// error

	A a2(2);
	B b2(2);

	A a3 = { 1, 2 };
	B b3 = { 1, 2 };	// error

	A a4{ 1, 2 };
	B b4{ 1, 2 };

	A a5 = (A)(1);
	B b5 = (B)(1);

 

 

'='의 오른쪽에 있는 표현식을 통하여 해당 객체를 만들어 초기화 하는 방법은 전부 error이다.

다만 b5의 경우엔, 1를 B로 casting 한 후 b5에 넣는 거니 copy 'initialization' 이 아닌 단순 copy assignment라 error가 뜨지 않는다.

 

 

 

 

또 만약, 해당 A나 B를 parameter로 받는 함수가 있다고 해 보자.

해당 함수에다 값을 넣어주면

 

int main() {

	A a1{ 1 };

	auto funcForA = [&](A) {return true; };

	funcForA(a1);
	funcForA(3);
	funcForA({ 4,5 });


	B b1{ 1 };

	auto funcForB = [&](B) {return true; };

	funcForB(b1);
	funcForB(3);		// error
	funcForB({ 4,5 });	// error


	return 0;
}

 

 

 

위 explicit를 쓰지 않은 A에서는, 넘겨 준 argument에 따라서 알아서 초기화가 된다.

하지만 explicit를 쓴 B에서는, B 타입이 아닌 모든 것들을 error로 바꿔버린다.

 

 

이렇게 하면 암시적으로 형변환이 되는 것을 막아줘서 좀 더 안전하게 코드를 짤 수 있다.

 

 

물론 그만큼 조금 더 귀찮아지긴 하겠다만..

 

 

 

https://en.cppreference.com/w/cpp/language/explicit

 

explicit specifier - cppreference.com

[edit] Syntax explicit (1) explicit ( expression ) (2) (since C++20) 2) The explicit specifier may be used with a constant expression. The function is explicit if and only if that constant expression evaluates to true. (since C++20) The explicit specifier

en.cppreference.com

 

 

 

*잘못된 정보는 덧글로 알려주세요!

반응형

'C++ > 기타' 카테고리의 다른 글

[C++] DLL로 class export / import - 1  (0) 2023.03.16
[C++ Metaprogramming] enable_if / enable_if_t  (0) 2023.03.07
[C++ String] string 나누기. string split  (0) 2023.03.04
[C++ keyword] noexcept  (0) 2023.03.02
Virtual 소멸자 이유  (0) 2022.05.16