如何扩展一个编译器生成的复制构造函数 [英] How can I extend a compiler generated copy constructor

查看:114
本文介绍了如何扩展一个编译器生成的复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到这个问题,我必须扩展一个编译器生成的复制构造函数。示例:

I frequently run into the problem, that I must extend a compiler generated copy constructor. Example:

class xyz;
class C
{
    ...
    int a, b, c; 
    std::set<int> mySet;
    xyz *some_private_ptr;
};

假设 some_private_ptr 在一定条件下。对于其他条件,它应该复制到 NULL 。所以我必须写一个复制构造函数像:

Assume, that some_private_ptr should only be copied under certain conditions. For other conditions it should be reset to NULL on copy. So I have to write a copy constructor like:

C::C(const C &other) : 
     a(other.a), 
     b(other.b), 
     c(other.c), 
    mySet(other.mySet)
{      
   if(CanCopy(other.some_private_ptr)) // matches condition
      some_private_ptr = other.some_private_ptr;
   else
      some_private_ptr = NULL;
}

问题是类可能有多个数据成员,我很可能会忘记更新复制构造函数,当我添加一个数据成员。这将是非常好的,如果我只是可以写。

The problem is that the class might have a number of data members, and that I very likely may forget to update the copy constructor when I add a data member. It would be very nice if I just could write.

C::C(const C &other) :
   C::default_copy(other)
{      
   if(CanCopy(other.some_private_ptr)) // matches condition
      some_private_ptr = other.some_private_ptr;
   else
      some_private_ptr = NULL;
}

这将使我的代码更安全,更容易维护。不幸的是我不知道这样的可能性。在你定义自己的拷贝ctor的时候,编译器不会为你生成一个拷贝ctor。

This would make my code more safe and easier to maintain. Unfortunately I don't know of such a possibility. Is there any?

推荐答案

不幸的是,这意味着你必须自己做所有的腿工作!您可以将成员分组到类中的某种 impl _ 结构,然后依靠复制ctor。

the moment you define your own copy ctor, the compiler does not bother generating one for you. Unfortunately this means you have to do all the leg work yourself! You could group the members into some sort of impl_ structure within your class, and then rely on the copy ctor for that.

例如:

class xyz;
class C
{
  struct impl_
  {
    int a, b, c; 
    std::set<int> mySet;
    xyz *some_private_ptr;
  };

  impl_ data;
};

现在在您的副本中

C::C(const C &other) : data(other.data)
{
 // specific stuff...      
}

这篇关于如何扩展一个编译器生成的复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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