0

If I have in my .h file

class A
{
 ...
protected:
static std::mutex someMutex;
}

What is proper way to instantiate it in the cpp file? Just to write

std::mutex A::someMutex;

? It works, but just such syntax where I basically declare a field twice feels a bit confusing, so I decided to doublecheck asking here, also maybe there are some other(better?) ways?

DoehJohn
  • 201
  • 1
  • 8
  • Have you tried it? Yes, that should work. – Mark Ransom May 30 '20 at 18:24
  • @MarkRansom yes, it works, but just such syntax where I basically declare a field twice feels a bit confusing, so I decided to doublecheck asking here, also maybe there are some other(better?) ways – DoehJohn May 30 '20 at 18:31
  • Does this answer your question? [Static constant string (class member)](https://stackoverflow.com/questions/1563897/static-constant-string-class-member) – JaMiT May 30 '20 at 20:09

1 Answers1

1

What you did is correct but these two notations are not exactly the same thing written twice.

Inside the braces of the class (in the .h file) this is a declaration.
It is a kind of promise saying "I swear this exists somewhere".
This can be seen in many translation units (i.e. .cpp files including this .h file).

On the other hand, what you wrote in your .cpp file is the definition of this variable; it must exist exactly once in your program.

An alternative exists since C++17: inline variables.
It offers the ability to skip the definition of the static variable in the .cpp file (useful for header-only solutions).

prog-fh
  • 13,492
  • 1
  • 15
  • 30