问题
I'm curious if the default constructor and destructor that the compiler generates are inline or not, because I can justify it either way. On the one hand, you want the default constructor/destructor to not be inline so that adding them later doesn't break ABI (because object files compiled when only the defaults were there will have inlined the generated definitions instead of what you define). On the other hand, for a C++ compiler to compile C code that performs as well as when compiled with a C compiler, it can't be adding constructor/destructor calls for every allocated struct, and in C++ the only functional difference between a class and a struct is supposed to be the default access protection. Maybe the linker addresses this somehow? Maybe the answer varies across compilers?
A consequence of this question: if I have a POD struct in C++, can I theoretically benefit under some compilers by defining empty inline constructor/destructors myself in place of the defaults?
回答1:
The C++ standard says, in 12.1[class.ctor]/5
An implicitly-declared default constructor is an inline public member of its class
and in 12.4[class.dtor]/3
An implicitly-declared destructor is an inline public member of its class.
回答2:
if I have a POD struct in C++, can I theoretically benefit under some compilers by defining empty inline constructor/destructors myself in place of the defaults?
Theorotically, Yes! Any function(including constructors & destructors) can be declared inline, and putting the function body in the class definition is one way of doing that. However, it's up to the compiler if it actually does inline the function.
回答3:
It varies across compilers, but in general: yes, they should.
With gcc at least, you get both an inline and an out-of-line function generated. The out-of-line version is marked as "link once", so no matter how many objects generate a default constructor, at most only one version will end up in the linked output. If in fact nobody uses the default constructor out-of-line, it's not included in the linked output at all, and you have effectively a purely inline function.
来源:https://stackoverflow.com/questions/6273958/are-the-default-constructor-and-destructor-ever-inline