상세 컨텐츠

본문 제목

[C++11] Attributes

C++/Modern C++(11, 14, 17, 20)

by deulee 2023. 8. 25. 20:36

본문

"Attributes"는 C++11에서 새로 도입된 기능으로 코드에 추가 정보를 제공하는 방법으로, 컴파일러에게 특정한 힌트나 지시 사항을 제공하거나, 코드의 동작을 제어하거나, 최적화를 조정하는 등의 목적으로 사용된다.

 

이를 통해 코드를 더 명확하게 작성하거나 컴파일러에게 추가적인 정보를 제공할 수 있다.

 

형식은 다음과 같다.

[[attribute]]

여기서 `attribute`는 사용하고자 하는 실제 속성의 이름이 들어간다. 여기에는 다양한 종류가 있는데 예시를 들자면 `[[noreturn]]`,`[[deprecated]]` 등이 있다.

 

예시)

#include <iostream>

// 항상 예외를 던지므로 반환되지 않는다.
[[noreturn]] void f() {
	throw "error";
}

// 무한 루프에 빠지기 때문에 반환되지 않는다.
[[noreturn]] void f2() {
	while (1) {}
}

[[deprecated("This function is deprecated. Use newFunction() instead")]]
void oldFunction() {
	std::cout << "This is the old function." << std::endl;
}

void newFunction() {
	std::cout << "This is the new function." << std::endl;
}

int main(void)
{
	oldFunction(); // 컴파일러가 경고를 표시할 수 있음.
	newFunction(); // 정상 호출
	return 0;
}

 

추가적인 Attributes들을 보고 싶다면 다음 페이지를 확인해보자.

 

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

 

Attribute specifier sequence(since C++11) - cppreference.com

Introduces implementation-defined attributes for types, objects, code, etc. [edit] Syntax [[ attribute-list ]] (since C++11) [[ using attribute-namespace : attribute-list ]] (since C++17) where attribute-list is a comma-separated sequence of zero or more a

en.cppreference.com

 

'C++ > Modern C++(11, 14, 17, 20)' 카테고리의 다른 글

[C++11] nullptr  (0) 2023.08.26
[C++11] Strongly-typed enums  (0) 2023.08.26
[C++11] constexpr  (0) 2023.08.25
[C++11] Delegating Constructors  (0) 2023.08.25
[C++11] User-defined literals  (0) 2023.08.25

관련글 더보기