简体   繁体   English

C ++中的“几乎默认”复制构造函数(&赋值运算符)

[英]“Almost default” copy constructor (& assignment operator) in C++

A common thing I find myself doing is making "almost default" copy constructors and assignment operators. 我发现自己做的一件常见的事情是制作“几乎默认”的复制构造函数和赋值运算符。 That is, I find myself in situations where the compiler supplied copy and assignment operators would work for most of the data members, but there's a particular data member which needs to be handled differently. 也就是说,我发现自己处于编译器提供的复制和赋值运算符适用于大多数数据成员的情况,但是有一个特定的数据成员需要以不同的方式处理。 This means that I have to explicitly create a copy constructor/assignment operator, including explicitly listing all the data members which have simple copy semantics. 这意味着我必须显式创建一个复制构造函数/赋值运算符,包括显式列出具有简单复制语义的所有数据成员。 This can get annoying for classes where there are a fair number of data members, or later on when member variables are added but aren't added to the copy constructor/assignment operator. 对于存在大量数据成员的类,或者稍后添加成员变量但未添加到复制构造函数/赋值运算符的类时,这会很烦人。

Is there some way to tell the C++ compiler that an explicitly declared copy constructor/assignment operator should work like an implicit one, except for some additional code that's run afterwards? 有没有办法告诉C ++编译器显式声明的复制构造函数/赋值运算符应该像隐式运算符一样工作,除了之后运行的一些额外代码? (And is such a syntax C++98 compatible, or does it need C++11 or C++14 support?) (并且这样的语法与C ++ 98兼容,还是需要C ++ 11或C ++ 14支持?)

If you can isolate the specific handling in a proper RAII wrapper as Igor Tandetnik suggested: go for that. 如果你可以像Igor Tandetnik建议的那样在适当的RAII包装中隔离特定的处理:那就去做吧。

If you still need specific processing in the copy constructor and/or assignment operator (such as register the object creation/assignment in a container or log), you can group the data members that can be default copy constructed/assigned into a separate class that you use as a base class or data member, which you handle as composite, thus: 如果您仍需要在复制构造函数和/或赋值运算符中进行特定处理(例如在容器或日志中注册对象创建/赋值),则可以将可以构造/赋值的默认副本的数据成员分组到一个单独的类中您用作基类或数据成员,您将其作为复合处理,因此:

struct x_base {
  int a,b,c,d;
  std::string name;
};

struct x : x_base {
     x(const x& other)
         : x_base(other) 
     {
         descr = "copied ";
         descr += name;
         descr += " at ";
         descr += CurrentTimeAsString();
         std::cout << descr << "\n";
     }
     void operator = (const x& other)
     {
         x_base::operator =(other); 
         descr = "assigned ";
         descr += name;
         descr += " at ";
         descr += CurrentTimeAsString();
         std::cout << descr << "\n";
     }
     std::string descr;
};

When you later add data members that don't need specific handling, you can simply add them to x_base. 稍后添加不需要特定处理的数据成员时,只需将它们添加到x_base即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM