cppcoder
cppcoder

Reputation: 1204

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?

Upvotes: 6

Views: 4343

Answers (3)

bobestm
bobestm

Reputation: 1334

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

Unless you wish to access the static variable in all instances of the class, there is no need to declare it static.

Upvotes: 0

Baltasarq
Baltasarq

Reputation: 12212

A static member is shared among all the instances of a class, so it does not make sense to initialize it in the constructor, nor copy it in the copy constructor.

Upvotes: 6

juanchopanza
juanchopanza

Reputation: 227518

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.

Upvotes: 15

Related Questions