inline:
strtuc MyType {
inline static std::string msg{"OK"};
};
struct MyType {
int value;
MyType(int i) : value{i} { }
static MyType max; // OK
inline static MyType min{0}; // Error
};
inline MyType MyType::max{0};
constexpr Now Implies inline For Static MembersD::n.
#include<iostream>
struct D {
static constexpr int n{5};
};
// It needs an actual object with storage to bind the reference to D::n
// Program needs its address / identity / memory location. (ODR-use)
int twice1(const int& i) {
return i;
}
int twice2(const int i) {
return i;
}
int main() {
std::cout << D::n << "\n"; // OK, before and after C++17
std::cout << twice1(D::n) << "\n"; // Error, before C++17 without optimization
std::cout << twice2(D::n) << "\n"; // OK, before and after C++17
}
thread_localBy using thread_local you can also make an inline variable unique for each thread:
#include<iostream>
#include<thread>
struct MyData {
inline static std::string gName{"global"}; // unique per program
inline static thread_local std::string tName{"tls"}; // unique per thread
std::string lName{"local"}; // unique per object
void print(const std::string& msg) const {
std::cout << msg << '\n';
std::cout << "gName: " << gName << '\n';
std::cout << "tName: " << tName << '\n';
std::cout << "lName: " << lName << '\n';
}
};
inline thread_local MyData myThreadData; // unique per thread
void foo()
{
myThreadData.print("foo()begin:");
myThreadData.gName = "thread2 name";
myThreadData.tName = "thread2 name";
myThreadData.lName = "thread2 name";
myThreadData.print("foo() end:");
}
int main() {
myThreadData.print("main() begin:");
// main() begin:
// gName = global
// tName = tls
// lName = local
myThreadData.gName = "thread1 name";
myThreadData.tName = "thread1 name";
myThreadData.lName = "thread1 name";
myThreadData.print("main() later:");
// main() later:
// gName = thread1 name
// tName = thread1 name
// lName = thread1 name
std::thread t(foo);
// foo() begin:
// gName = thread1 name
// tName = tls
// lName = local
// foo() end:
// gName = thread2 name
// tName = thread2 name
// lName = thread2 name
t.join();
myThreadData.print("main() end:");
// main() end:
// gName = thread2 name
// tName = thread1 name
// lName = thread1 name
}