I have a class with a container that is declared static:
class test {
public:
test(const ClassA& aRef, const std::string& token);
test(const test& src);
~test();
private:
ClassA& m_ObjRef;
static std::vector<std::string> s_toks;
};
The s_toks container is initialized as follows in the constructor defined in test.cpp:
std::vector<std::string> test::s_toks;
test::test(const ClassA& aRef, const std::string& token)
: m_ObjRef(aRef)
{
my_tokenize_function(token, s_toks);
}
test::test(const test& src)
: m_ObjRef(src.m_ObjRef)
{
/* What happens to s_toks; */
}
If I do not copy s_toks, and s_toks is accessed from the new copied object, it is empty. What's the correct way to handle this?
A static data member is not bound to a single instance of your class. It exists for all instances, and to attempt to modify it in the class copy constructor makes little sense (unless you are using it to keep some kind of counter of instances). By the same token, it makes little sense to "initialize" it in any of the class constructors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With