In C ++, can a constructor and destructor be inline functions?

VC ++ creates functions that are implemented inside the built-in functions of the class declaration.

If I declare a Foo class as follows, are the CONSTRUCTOR and DESTRUCTOR built-in functions?

 class Foo { int* p; public: Foo() { p = new char[0x00100000]; } ~Foo() { delete [] p; } }; { Foo f; (f); } 
+57
c ++ constructor destructor
Aug 21 '08 at 22:02
source share
5 answers

Defining the constructor body of an INSIDE class has the same effect as placing an OUTSIDE function of a class with the keyword "inline".

In both cases, this is a hint for the compiler. A β€œbuilt-in” function does not necessarily mean that the function will be built-in. It depends on the complexity of the function and other rules.

+56
Aug 21 '08 at 22:10
source share
β€” -

The short answer is yes. Any function can be declared inline, and one way to do this is to use the body of the function in the class definition. You could also do:

 class Foo { int* p; public: Foo(); ~Foo(); }; inline Foo::Foo() { p = new char[0x00100000]; } inline Foo::~Foo() { delete [] p; } 

However, it is up to the compiler if it really performs an inline function. VC ++ largely ignores your inlining requests. It will only be a built-in function if she thinks it is a good idea. In the latest versions of the compiler, elements that are in separate .obj files and are not declared inline (for example, from code in different .cpp files) will also be embedded if you use the code generation link time .

You can use the __ forceinline keyword to tell the compiler that you really mean it when you say "embed this function", but it’s usually not worth it. In many cases, the compiler really knows better.

+24
Aug 21 '08 at 22:12
source share

Including a function definition in a class body is equivalent to marking a function with the inline keyword. This means that the function may or may not be embedded in the compiler. So, I think the best answer would be "maybe"?

+2
Aug 21 '08 at 22:11
source share

To the same extent that we can do any other built-in function, yes.

+1
Aug 21 '08 at 22:12
source share

Embedding or not is mainly determined by your compiler. The built-in code only hints at the compiler.
One rule you can count on is that virtual functions will never be inlined. If your base class has a virtual constructor / destructor, yours will probably never be inline.

+1
Oct 21 '08 at 16:00
source share



All Articles