简体   繁体   中英

How properly instantiate static field tat is another class object

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?

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 (ie .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).

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