Should a static member be copied in the copy constructor, and if so, how to do it?

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 accessible from the newly copied object, it is empty. What is the right way to handle this?

+4
source share
3 answers

A static data member is not bound to a single instance of your class. It exists for all instances, and trying to modify it in the class copy constructor makes little sense (unless you use it to store some kind of instance counter). Similarly, it makes no sense to "initialize" it in any of the class constructors.

+13
source

The static member is distributed among all instances of the class, so it makes no sense to initialize it in the constructor and not copy it in the copy constructor.

+6
source

Supporting other people's comments, this link provides a good explanation of the examples: http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

If you do not want to access the static variable in all instances of the class, there is no need to declare it static.

0
source

Source: https://habr.com/ru/post/1485700/


All Articles