简体   繁体   中英

C++ pimpl idiom and static method and fields

I would like to better understand how to use static field an method in the presence of PIMPL idiom. Consider the following code.

MyClass.h file:

#ifndef MYCLASS
#define MYCLASS

class MyClass{
     public:
     void method();
     static void static_method();

     private:
     Type field;
     static Type *static_field;
}

#endif

MyClass.cpp file:

#include MyClass.h

void MyClass::method(){
     /*OK method definition*/
     field = new Type();   /*OK field construction*/
}

void MyClass::static_method(){
     /*NOT WORKING method declaraion */
     static_field = new Type();   /*not working */
}

I have these 2 errors:

  1. cannot declare member function static_method to have a static linkage
  2. static_field was not declared in this scope

I'm not very familiar with pimpl idiom.

So my question is how I achieve static methods and fields declarations to respect the PIMPL idiom and compile it successfully?

What am I doing wrong in this code?

How have I to change my code?

The purpose if pimpl is to eliminate compilation dependencies. The fact that a pimpl class has a private static member is an implementation detail and thus should not be in the header file or in the pimpl class definition.

Put you private statics into the .cc/.cpp file in an unnamed namespace along with the definitions of the member functions of the pimpl class.

  • Show us actual code that you've verified produces the same error
  • Don't put static in front of the function definition in the .cpp file
  • You don't have a static_field - you have two field

Indeed, u need to have the definiton

Type* MyClass::static_field = new Type();

at u'r cpp file. this is because this way u tell the compiler at what object file the field should be instantiated, otherwise the compiler has no way to know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM