[英]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: 我有一个带有声明为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: s_toks容器在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. 如果我不复制s_toks,并且从新复制的对象访问s_toks,则它为空。 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.
出于同样的原因,在任何类构造函数中“初始化”它都没有意义。
静态成员在类的所有实例之间共享,因此在构造函数中初始化它是没有意义的,也不会在复制构造函数中复制它。
Supporting other people's comments, this link provide a good explanation with examples: http://www.learncpp.com/cpp-tutorial/811-static-member-variables/ 支持其他人的评论,这个链接提供了一个很好的解释与例子: 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. 除非您希望在类的所有实例中访问静态变量,否则无需将其声明为静态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.