What is the best way to have a static member in a non-templated library class,
without placing the burden of defining the member on the class user?
Say I want to provide this class:
class i_want_a_static_member
{
static expensive_resource static_resource_;
public:
void foo()
{
static_resource_.bar();
}
};
Then the user of the class must not forget to define the static member somewhere
(as already answered many times):
// this must be done somewhere in a translation unit
expensive_resource i_want_a_static_member::static_resource_;
I do have an answer below, but it has some disadvantages. Are there better and/or more elegant solutions?
C++17 and above
Use inline static variables for non-dynamic initialization:
struct Foo
{
inline static int I = 0;
};
And use function local static variables otherwise:
struct Foo
{
static std::string& Bar()
{
static std::string S = compute();
return S;
}
};
C++14 and below
Use function local statics, as they are plain easier to use.
If for some reason you really wish for a static data member, then you can use the template trick:
template <typename T = void>
struct Foo
{
static int I = 0; // inline initialization only for simple types.
};
template <typename T>
int Foo<T>::I;
On local statics
For resources which require dynamic initialization, it is best to use a local static.
The order in which file-scope or class-scope statics are dynamically initialized is undefined, in general, leading to the Static Initialization Order Fiasco when you try to read a uninitialized static as part of the initialization of another. Local static solve the issue by being initialized lazily, on first use.
There is some slight overhead to using local statics, however. From C++11 onwards, the initialization is required to be thread-safe, which typically means that any access is gated by an atomic read and well-predicted branch.
My own solution is to use a templated holder class, as static members work fine in templates, and use this holder as a base class.
template <typename T>
struct static_holder
{
static T static_resource_;
};
template <typename T>
T static_holder<T>::static_resource_;
Now use the holder class:
class expensive_resource { /*...*/ };
class i_want_a_static_member : private static_holder<expensive_resource>
{
public:
void foo()
{
static_resource_.bar();
}
};
But as the name of the member is specified in the holder class, you can't use the same holder for more than one static member.
As of C++ 17. You can now use inline variables to do this:
static const inline float foo = 1.25f;
Related
class TestClass
{
public:
static int testMember;
template<class T> static T* Foo()
{
//Defination....
}
}
//int TestClass::testMember; //Duplicate definition
Why can't I define a member field in .hpp while I can define member functions in .hpp?
Does it must be defined in a .cpp file?
Why can't I define a member field in .hpp
You can.
C++ doesn't care what you name your files, and doesn't care what extension the files have.
What you can't do is define the variable more than once. That would obviously violate the one definition rule.
In order to satisfy the one definition rule, you have two options:
In C++17 or later, make the variable inline.
class TestClass
{
public:
static inline int testMember;
template<class T> static T* Foo()
{
//Defination....
}
}
In any version of C++, place the definition in your code where it will be compiled exactly once.
Why ... [can I] define member functions in .hpp?
Because member functions, defined in the class, are implicitly inline. Just like your variable could be.
As Drew Dormann has mentioned, template member functions (static or not) are implicitly inline.
The same goes for class templates:
template <typename>
class TestClass
{
public:
static int testMember;
template<class T> static T* Foo()
{
//Definition....
}
};
// prior to C++17 you definition MUST be outside the class in the header
template <typename T>
int TestClass<T>::testMember{};
This question already has answers here:
Why static variable needs to be explicitly defined?
(5 answers)
Closed 2 years ago.
So I have this file
template <typename T>
class TestStatic {
public:
static int staticVal;
};
//static member initialization
template<typename T> int TestStatic<T>::staticVal;
I don’t understand why I have to instantiate the Staticval isn’t it already instantiated in the class definition? Also does it generate a static variable for each template parameter types?
Thanks in advance.
This line:
static int staticVal;
inside the class is a declaration, not a definition. That's why you have to define it outside the class like this:
template<typename T>
int TestStatic<T>::staticVal = 0;
And yes, this will generate a definition of the member for all types T.
Alternatively, you could define the static variable inline, like this:
template <typename T>
class TestStatic {
public:
inline static int staticVal = 0;
};
which has the same semantics as above, but let's you avoid having to define the static variable separately outside the class.
As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of the same static variables for different objects. Also because of this reason static variables can not be initialized using constructors.
Please refer for more information: Reference
As reported in this Q&A, const static member functions are/were not available in C++. Did anything change since then (2011)?
Is there another way to have static member functions that do not modify the static members of their class?
Something like (pseudo-code):
class C
{
static int a;
public:
static void Incr() { ++a; }
static int Ret() const { return a; }
};
int C::a = 0;
I would need to call a [const] static member function from another class' const member function.
According to the current cppreference.com (page about static members), static member functions still cannot be const, because the const keyword only modifies the this pointer, which static functions obviously do not have.
So nothing seems to have changed since the answer you were referring to was written.
Did anything change since then (2011)?
Nothing changed, you still can't cv-qualify a static member function.
Is there another way to have static member functions that do not modify the static members of their class?
Not a perfect solution, but you may declare const "aliases" to static data members:
static int Ret() {
static constexpr const auto& a = C::a;
// Now C::a is shadowed by the local a
// and the function can't modify it.
// a = 2; // ill-formed
return a * 2; // OK
}
It still requires discipline, but at least that way a compiler can catch unintended modification attempts.
Class which has only static fields and static methods doesn't deserve to be called class. It is just form of functions and global variables with fancy name spacing.
Anyway IMO it is much better to have a regular class with regular fields and methods and then instantiate it as a global variable (not very nice solution, but at least more honest where class contains only static fields and methods).
class C
{
int a;
public:
C() : a(0) {}
void Incr() { ++a; }
int Ret() const { return a; }
};
C instance;
Or use singleton pattern which I hate.
From generated code perspective there should be no difference.
What is wrong with this implementation in header file?
template <typename T>
class Singleton
{
public:
static T* getInstance()
{
if (m_instance == NULL)
{
m_instance = new T();
}
return m_instance;
}
private:
static T* m_instance;
};
I use it like this:
typedef Singleton<MyClass> MyClassSingleton;
I get linker error:
error LNK2001: unresolved external symbol "private: static class MyClass * Singleton<class MyClass>::m_instance" (?m_instance#?$Singleton#VMyClass####0PAVMyClass##A)
When I add
template <typename T> T* Singleton<T>::m_instance = NULL;
it works, but I worry on two things:
Static member should be defined in .cpp file in order to have only one instance in all compilation units, even if you include the header file into 10 source files
Pointers are being initialized to NULL by standard, why I need to explicitly initialize?
You can fix your error by adding a definition for the m_instance member after the class definition.
template<typename T>
T* Singleton<T>::m_instance = nullptr;
For class templates, it's OK to add the definition of static members within the header itself, and won't lead to ODR violations.
But, as others have suggested, it's best to change you getInstance() definition to
static T& getInstance()
{
static T instance;
return instance;
}
C++11 even guarantees that the creation of the function local static variable instance will be thread-safe.
Static members always need to be initialized exactly once, including those from template instantiations.
You can avoid this with local statics if you really like:
template <typename T>
T *Singleton<T>::getInstance() {
// Will be lazy initialized on first call (instead of startup) probably.
static T instance;
return &instance;
}
Or:
// No need to use pointers, really...
template <typename T>
T &Singleton<T>::getInstance() {
static T instance;
return instance
};
If you're really want to use a singleton, and you're really sure you want to use a templated singleton, you may want to use Scott Meyer's singleton approach:
template <typename T>
class Singleton
{
public:
static Singleton<T>& getInstance() {
static Singleton<T> theInstance;
return theInstance;
}
private:
Singleton() {}
Singleton(const Singleton<T>&);
Singleton<T>& operator=(const Singleton<T>&);
};
Pointers are being initialized to NULL by standard, why I need to
explicitly initialize?
You don't need.
template <typename T>
T* Singleton<T>::m_instance;
This will suffice as static & global variables are zero initialized by default
Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5)
before any other initialization takes place.
Others have answered how to fix the code, but your question was also about the reasoning. By way of explanation, what you are struggling with is the difference between declaration and definition. In this line:
static T* m_instance;
You are declaring that there is a name for m_instance, but you have not defined the space. The line of code you added defines the space.
We have a singleton template class as defines below
template<class T> class Singleton{
T& reference(){
return objT;
}
private:
T objT;
};
And another user defined class which uses this singleton
class TestClass{
static Singleton<TestClass> instance;
static TestClass * getPointer()
{
return &instance.objT;
}
private:
TestClass(){}
};
template<TestClass>
Singleton<TestClass> TestClass::instance;
On compilation with GCC we are getting the error
In function static_initialization_and_destruction undefined reference to Singleton::Singleton().
What can be the reason for this.
Ignoring the fact, that in your example there is no need for Singleton template, consider this simplified example (I am using structs to avoid access issues):
template <class T>
struct Singleton
{
T object;
};
struct TestClass;
typedef Singleton<TestClass> TCS;
TCS test1; // not ok, no definition of TestClass available;
struct TestClass
{
TestClass(){}
static TCS test2; // not ok, no definition of TestClass available;
};
TCS test3; // ok, TestClass is defined;
To declare a member of type T, you need a complete definition of this type T. So, test1 and test2 are not legal - there is only a declaration, not definition of T. On the contrary, test3 is legal - it is located after the complete definition of the class. Easiest fix here is to use pointer to type - to declare a pointer to type T, you need a declaration instead of definition for the type T:
template <class T>
struct Singleton
{
T * object;
};
static Singleton<TestClass> instance;
you are actually trying to create an instance of class Singleton in above line; which will look for default constructor Singleton() (which is already present as you haven't explicitly defined it private).
T& reference() is a private method in your class.
And I didn't really understand this
template<TestClass>
Singleton<TestClass> TestClass::instance;
Are you sure what you are trying to do? Cause am not ;)
Maybe you want to read this to understand what you are doing http://www.yolinux.com/TUTORIALS/C++Singleton.html
Easiest fix: Don't use a singleton.