Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does static member need to be copied in copy constructor and if yes, 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 accessed from the new copied object, it is empty. What's the correct way to handle this?

like image 291
cppcoder Avatar asked Nov 30 '22 03:11

cppcoder


1 Answers

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.

like image 194
juanchopanza Avatar answered Dec 05 '22 07:12

juanchopanza