c++ - inline放在哪好

来源:互联网 发布:js通过数据库表单验证 编辑:程序博客网 时间:2024/06/10 00:09

Best practice: only in the definition outside the class body.

 class Foo {
 public:
   void method();  
 best practice: don't put the inline keyword here
   
...
 };
 
 inline void Foo::method()  
 best practice: put the inline keyword here
 { ... }

Here's the basic idea:

  • The public: part of the class body is where you describe the observable semantics of a class, its public member functions, its friend functions, and anything else exported by the class. Try not to provide any inklings of anything that can't be observed from the caller's code.
  • The other parts of the class, including non-public: part of the class body, the definitions of your member and friend functions, etc. are pureimplementation. Try not to describe any observable semantics that were not already described in the class's public: part.

From a practical standpoint, this separation makes life easier and safer for your users. Say Chuck wants to simply "use" your class. Because you read this FAQ and used the above separation, Chuck can read your class's public: part and see everything he needs to see and nothing he doesn't need to see. His life is easier because he needs to look in only one spot,and his life is safer because his pure mind isn't polluted by implementation minutiae.

Back to inline-ness: the decision of whether a function is or is not inline is animplementation detail that does not change the observable semantics (the "meaning") of a call. Therefore the inline keyword should go next to the function's definition, not within the class'spublic: part.



http://www.parashift.com/c++-faq-lite/inline-functions.html