开发者

C++ pimpl idiom and static method and fields

开发者 https://www.devze.com 2023-02-20 01:01 出处:网络
I would like to better understand how to use static field an method in the presence of PIMPL idiom. Consider the following code.

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 declarati开发者_StackOverflowons 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消