C ++ 11에서 사용되지 않는 매개 변수
C ++ 03 및 이전 버전에서는 사용되지 않는 매개 변수에 대한 컴파일러 경고를 비활성화하기 위해 일반적으로 다음 코드를 사용합니다.
#define UNUSED(expr) do { (void)(expr); } while (0)
예를 들면
int main(int argc, char *argv[])
{
UNUSED(argc);
UNUSED(argv);
return 0;
}
그러나 매크로는 C ++의 모범 사례가 아닙니다. C ++ 11 표준에 더 나은 솔루션이 있습니까? 매크로를 제거 할 수 있습니까?
모두 감사합니다!
그 목적을 위해 빈 본문이있는 함수를 사용했습니다.
template <typename T>
void ignore(T &&)
{ }
void f(int a, int b)
{
ignore(a);
ignore(b);
return;
}
심각한 컴파일러가 함수 호출을 최적화하기를 기대하고 경고를 표시하지 않습니다.
매개 변수 이름을 생략 할 수 있습니다.
int main(int, char *[])
{
return 0;
}
그리고 main의 경우 매개 변수를 모두 생략 할 수도 있습니다.
int main()
{
// no return implies return 0;
}
C ++ 11 표준의 "§ 3.6 시작 및 종료"를 참조하십시오.
거기 <tuple>
에 C ++ (11) 사용에 대한 준비를 포함, std::ignore
의는 (런타임 오버 헤드를 부과하지 않고 가능성이 매우 높다) 쓰기 우리를 허용하는지, 객체 :
void f(int x)
{
std::ignore = x;
}
동등한 것은 없습니다.
그래서 당신은 똑같은 오래된 옵션을 고수하고 있습니다. 매개 변수 목록에서 이름을 완전히 생략 할 수 있습니까?
int main(int, char**)
main
물론 의 특정 경우에는 단순히 매개 변수 자체를 생략 할 수 있습니다.
int main()
GCC와 같은 일반적인 구현 관련 트릭도 __attribute__((unused))
있습니다.
이 경고를 "비활성화"하려면 인수 작성을 피하고 유형 만 작성하는 것이 가장 좋습니다.
void function( int, int )
{
}
또는 원하는 경우 주석 처리 :
void function( int /*a*/, int /*b*/ )
{
}
명명 된 인수와 명명되지 않은 인수를 혼합 할 수 있습니다.
void function( int a, int /*b*/ )
{
}
로 17 ++ C 당신이 [[maybe_unused] 속성 지정, 같은 :
void function( [[maybe_unused]] int a, [[maybe_unused]] int b )
{
}
매크로는 이상적이지 않을 수 있지만 이러한 특정 목적에 적합합니다. 나는 매크로 사용을 고수하고 싶다.
구식 및 표준 방식에 대해 무엇을 가지고 있습니까?
void f(int a, int b)
{
(void)a;
(void)b;
return;
}
새로운 것이 없습니다.
What works best for me is to comment out the parameter name in the implementation. That way, you get rid of the warning, but still retain some notion of what the parameter is (since the name is available).
Your macro (and every other cast-to-void approach) has the downside that you can actually use the parameter after using the macro. This can make code harder to maintain.
The Boost header <boost/core/ignore_unused.hpp>
(Boost >= 1.56) defines, for this purpose, the function template boost::ignore_unused()
.
int fun(int foo, int bar)
{
boost::ignore_unused(bar);
#ifdef ENABLE_DEBUG_OUTPUT
if (foo < bar)
std::cerr << "warning! foo < bar";
#endif
return foo + 2;
}
PS C++17 has the [[maybe_unused]]
attribute to suppresses warnings on unused entities.
I really like using macros for this, because it allows you better control when you have different debug builds (e.g. if you want to build with asserts enabled):
#if defined(ENABLE_ASSERTS)
#define MY_ASSERT(x) assert(x)
#else
#define MY_ASSERT(x)
#end
#define MY_UNUSED(x)
#if defined(ENABLE_ASSERTS)
#define MY_USED_FOR_ASSERTS(x) x
#else
#define MY_USED_FOR_ASSERTS(x) MY_UNUSED(x)
#end
and then use it like:
int myFunc(int myInt, float MY_USED_FOR_ASSERTS(myFloat), char MY_UNUSED(myChar))
{
MY_ASSERT(myChar < 12.0f);
return myInt;
}
I have my own implementation for time critical segments of code. I've been researching a while a time critical code for slow down and have found this implementation consumes about 2% from the time critical code i have being optimized:
#define UTILITY_UNUSED(exp) (void)(exp)
#define UTILITY_UNUSED2(e0, e1) UTILITY_UNUSED(e0); UTILITY_UNUSED(e1)
#define ASSERT_EQ(v1, v2) { UTILITY_UNUSED2(v1, v2); } (void)0
The time critical code has used the ASSERT*
definitions for debug purposes, but in release it clearly has cutted out, but... Seems this one produces a bit faster code in Visual Studio 2015 Update 3
:
#define UTILITY_UNUSED(exp) (void)(false ? (false ? ((void)(exp)) : (void)0) : (void)0)
#define UTILITY_UNUSED2(e0, e1) (void)(false ? (false ? ((void)(e0), (void)(e1)) : (void)0) : (void)0)
The reason is in double false ?
expression. It somehow produces a bit faster code in release with maximal optimization.
I don't know why this is faster (seems a bug in compiler optimization), but it at least a better solution for that case of code.
Note: Most important thing here is that a time critical code slow downs without above assertions or unused macroses in release. In another words the double false ?
expression surprisingly helps to optimize a code.
windows.h defines UNREFERENCED_PARAMETER:
#define UNREFERENCED_PARAMETER(P) {(P) = (P);}
So you could do it like this:
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv) {
UNREFERENCED_PARAMETER(argc);
puts(argv[1]);
return 0;
}
Or outside of Windows:
#include <stdio.h>
#define UNREFERENCED_PARAMETER(P) {(P) = (P);}
int main(int argc, char **argv) {
UNREFERENCED_PARAMETER(argc);
puts(argv[1]);
return 0;
}
참고URL : https://stackoverflow.com/questions/15763937/unused-parameter-in-c11
'Nice programing' 카테고리의 다른 글
컴퓨터에있는 총 RAM 양은 어떻게 얻습니까? (0) | 2020.10.17 |
---|---|
WPF : 응용 프로그램의 중앙에 표시 할 대화 상자 위치를 설정하는 방법은 무엇입니까? (0) | 2020.10.17 |
쌍을 이루는 순환 파이썬 'for'루프 (0) | 2020.10.17 |
자바 스크립트에서 배열의 중복 값을 계산하는 방법 (0) | 2020.10.17 |
목록에 하나의 진실한 값만 있는지 어떻게 확인할 수 있습니까? (0) | 2020.10.17 |