“几乎默认" C ++中的复制构造函数(&赋值运算符) [英] "Almost default" copy constructor (& assignment operator) in C++

查看:128
本文介绍了“几乎默认" 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.

是否有某种方法可以告诉C ++编译器,除此后运行的其他一些代码外,显式声明的副本构造函数/赋值运算符应像隐式的那样工作? (并且这种语法C ++ 98是否兼容,还是需要C ++ 11或C ++ 14支持?)

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? (And is such a syntax C++98 compatible, or does it need C++11 or C++14 support?)

推荐答案

如果您可以按照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.

这篇关于“几乎默认" C ++中的复制构造函数(&amp;赋值运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆