且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-01 02:30:53

如果您可以按照Igor Tandetnik的建议,在适当的RAII包装中隔离特定的处理方法,那就去做吧.

If you can isolate the specific handling in a proper RAII wrapper as Igor Tandetnik suggested: go for that.

如果您仍需要在复制构造函数和/或赋值运算符中进行特定处理(例如在容器或日志中注册对象创建/赋值),则可以将可以默认复制构造/赋值的数据成员分组为一个用作基类或数据成员的单独类,可以将其作为复合类进行处理,因此:

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;
};

以后添加不需要特定处理的数据成员时,只需将它们添加到x_base.

When you later add data members that don't need specific handling, you can simply add them to x_base.