static global variable V static global Class variable
Which is way to declare a string const is more recommended?
The variable will be used only in the class member functions. I am tending to feel 2 is better since it is specific to the class member functions only.
A.cpp
---------------------
static const std::string hello_str = "Hello";
void A::print()
{
std::cout << hello_str;
}
(OR)
A.h
---------------------
class A{
public:
static const std::string hello_str;
void print();
}
A.cpp
---------------------
const std::string A::hello_str = "Hello";
void A::print()
{
std::cout << A::hello_str;
}
Edit -1:
Let me say that the contents of hello_str can change. Eg. the string is updated manually by the developer whenever he makes a change to the file.
In this case, would it make sense to keep the variable initialization inside a function? It may not be clear/evident for the user to update the string. If it was kept global to the file (1) or to the class (2) then other developers can "identify" & modify this string.
Given the above use case, do you still recommend having a function to return the string? Or can I use the class level static variable (with private access specifier)?
an anonymous namespace is another option:
A.cpp
namespace {
const std::string hello_str("Hello");
}
void A::print() {
std::cout << hello_str;
}
but you should really wrap that in a function for deferred initialization.
that would take the form:
A.h
---------------------
class A{
public:
static const std::string& hello_str();
void print();
}
A.cpp
---------------------
const std::string& A::hello_str() {
static const std::string str("Hello"); // << constructed on first call of A::hello_str()
return str;
}
void A::print() {
std::cout << A::hello_str();
}
in this case, you could also simply return by value, and avoid the static/global altogether. your std c++ library implementation may use what is call "small string optimization" -- if so, no heap allocation would be required to create or move a string this short.
also note that your two examples are not the same; one is effectively private, and the other is publicly visible.
ultimately, you should use neither approach you have proposed. consider a static within a function for lazy initialization, or (even better in many cases) returning by value.
to answer your original question: i favor the declaration inside the class, but private. i find this easier to maintain in the event implementations shift around. and of course, if that static in the cpp is somehow accessible to outside implementations, then you might want to also declare it as private inside the class so others cannot access it.
Simple rule:
string
logically belongs to the class so it should be a class member. static
member. This gives you the advantage that:
上一篇: C ++中的静态全局变量
下一篇: 静态全局变量V静态全局类变量