constexpr은 인라인을 의미합니까?
다음 인라인 함수를 고려하십시오.
// Inline specifier version
#include<iostream>
#include<cstdlib>
inline int f(const int x);
inline int f(const int x)
{
return 2*x;
}
int main(int argc, char* argv[])
{
return f(std::atoi(argv[1]));
}
및 constexpr 동등한 버전 :
// Constexpr specifier version
#include<iostream>
#include<cstdlib>
constexpr int f(const int x);
constexpr int f(const int x)
{
return 2*x;
}
int main(int argc, char* argv[])
{
return f(std::atoi(argv[1]));
}
내 질문은 : constexpr
지정자가 inline
상수가 아닌 인수가 constexpr
함수에 전달 되면 컴파일러가 지정자가 선언에 들어간 inline
것처럼 함수를 시도 한다는 의미에서 지정자를 암시 inline
합니까?
C ++ 11 표준이 보장합니까?
예 ([dcl.constexpr], C ++ 11 표준의 §7.1.5 / 2) : "constexpr 함수 및 constexpr 생성자는 암시 적으로 인라인 (7.1.2)입니다."
참고 그러나 것을 inline
지정 정말이 매우 컴파일러 가능성이 함수 인라인 여부를 확장하는 것입니다 여부에 (있는 경우) 거의 영향을. 그러나 이는 하나의 정의 규칙에 영향을 미치며 그 관점에서 컴파일러는 constexpr
함수와 동일한 규칙을 따라야합니다 inline
.
또한 constexpr
암시에 관계없이 C ++ 11의 함수에 inline
대한 규칙 constexpr
은 인라인 확장을위한 좋은 후보가 될 수있을 정도로 간단해야합니다 (주요 예외는 재귀적인 것임). 그러나 그 이후로 규칙은 점차 완화 constexpr
되어 훨씬 더 크고 복잡한 기능에 적용될 수 있습니다.
constexpr
inline
비 정적 변수 (C ++ 17 인라인 변수)를 의미하지 않습니다.
함수를 constexpr
암시 하지만 inline
C ++ 17 인라인 변수를 고려할 때 비 정적 변수에는 영향을주지 않습니다.
예를 들어, 내가 게시 한 최소한의 예제를 취한다면 : 인라인 변수는 어떻게 작동합니까? 를 제거 inline
하고을 남겨두면 constexpr
변수가 여러 주소를 가져옵니다. 이는 인라인 변수가 피하는 주요 사항입니다.
constexpr
그러나 정적 변수는 암시 적으로 정적입니다.
함수 를 constexpr
의미 inline
하는 최소한의 예
As mentioned at: https://stackoverflow.com/a/14391320/895245 the main effect of inline
is not to inline but to allow multiple definitions of a function, standard quote at: How can a C++ header file include implementation?
We can observe that by playing with the following example:
main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
assert(shared_func() == notmain_func());
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline int shared_func() { return 42; }
int notmain_func();
#endif
notmain.cpp
#include "notmain.hpp"
int notmain_func() {
return shared_func();
}
Compile and run:
g++ -c -ggdb3 -O0 -Wall -Wextra -std=c++11 -pedantic-errors -o 'notmain.o' 'notmain.cpp'
g++ -c -ggdb3 -O0 -Wall -Wextra -std=c++11 -pedantic-errors -o 'main.o' 'main.cpp'
g++ -ggdb3 -O0 -Wall -Wextra -std=c++11 -pedantic-errors -o 'main.out' notmain.o main.o
./main.out
If we remove inline
from shared_func
, link would fail with:
multiple definition of `shared_func()'
because the header gets included into multiple .cpp
files.
But if we replace inline
with constexpr
, then it works again, because constexpr
also implies inline
.
GCC implements that by marking the symbols as weak on the ELF object files: How can a C++ header file include implementation?
Tested in GCC 8.3.0.
참고URL : https://stackoverflow.com/questions/14391272/does-constexpr-imply-inline
'developer tip' 카테고리의 다른 글
C # : 정적 메서드가 여러 스레드에서 호출되면 어떻게됩니까? (0) | 2020.09.12 |
---|---|
WinForms의 Model-View-Presenter (0) | 2020.09.12 |
http 호스트 헤더 란 무엇입니까? (0) | 2020.09.12 |
MySQL "WITH"절 (0) | 2020.09.12 |
Java에서 Linux 쉘 명령을 호출하는 방법 (0) | 2020.09.12 |