Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constructor/destructor access error from static class field #1278

Open
fafner2000 opened this issue Apr 25, 2024 · 0 comments
Open

Constructor/destructor access error from static class field #1278

fafner2000 opened this issue Apr 25, 2024 · 0 comments

Comments

@fafner2000
Copy link

Hello,

I have an access error when trying to initialize a static class field with a private constructor of the same class (classical singleton pattern). I had the exact same problem at the exact same location when compiling with Visual Studio 6. I am not exactly using that compiler every day, so I never really cared about it. Now I have the same error with Watcom, which makes me wonder if I may be trespassing on some specification I don't know about. However, I made some searches and ended up only on (very old) posts from people having the problem with Visual Studio 6.

So here is the code:

class Singleton
  {
  private:
    inline Singleton() {}
    inline Singleton(int) {}
    inline ~Singleton() {}

  public:
    static const Singleton UNIQUE;
  };

const Singleton Singleton::UNIQUE;  // <-- access error here

Constructors and destructor are private to avoid "accidents". Changing their access to public solves the problem, but exposes to possible buggy code that would try to create or destroy what is supposed to be a singleton. I also tried to add the static keyword on front of the line, with no change. As it is, it compiles fine with all compilers I know (gcc, clang, RECENT versions of Visual Studio, etc; all spanning many versions).

However, Watcom gives me this error:
test.cpp(14): Error! E148: col(34) access to private member 'Singleton::Singleton' is not allowed

Additionally, it looks like I can somewhat get away with it by not using the default constructor, and writing:
const Singleton Singleton::UNIQUE=1;
const Singleton Singleton::UNIQUE(1); // same behavior with this variant

Giving this error:
test.cpp(14): Error! E148: col(36) access to private member 'Singleton::~Singleton' is not allowed

This time the (non-default) constructor seems to be accessible, but not the destructor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant