是否可以“添加”到默认的复制构造函数?

时间:2011-08-04 08:19:52

标签: c++ copy-constructor

是否可以“添加”到默认的复制构造函数?

EG。对于这堂课:

class A
{
    public:
        int a;
        int* b;
};

我想写一下

A::A(const A& rvalue):
    a(rvalue.a),
    b(new int(*(rvalue.b)))
{}

没有a(rvalue.a)部分。

(忽略糟糕/丑陋的代码和可能的内存泄漏)

3 个答案:

答案 0 :(得分:8)

你要求的是不可能的。一旦声明了自己的复制构造函数,编译器就不会为您生成复制构造函数。这意味着您将无法简单地添加或扩充默认的复制构造函数,因为它不存在。这可能是全部或全无。

答案 1 :(得分:5)

这是不可能的。但是,如果要减少大量“默认复制”字段的冗余代码,可以使用中间继承来实现:

struct A1  {
  int a1;
  int a2;
  // ....
  int aN;
};

struct A:public A1
{
  int* b;
  A(const A& rhs):  A1(rhs), b(new int(*(rhs.b))) {}
};

答案 2 :(得分:1)

C ++并不支持你想要做的事情:你不能拥有一半的默认构造函数。

但是你想要实现的目标可以通过下面的小技巧来完成:

请注意下面的这个小型演示有很多缺陷(内存泄漏等),所以它仅用于演示暂定解决方案:

//class A hasa large number date members(but all can take advantage of default 
//copy constructor
struct A{
    A(int i):a(i){}
    int a;
    //much more data memberS can use default copy constructor all in class A
};

//class B is simply wrapper for class A 
//so class B can use the default constructor of A
//while just write copy constructor for a raw pointer in it's copy constructor
//I think this is what OP want ?
struct B
{
    B(int i,int j):m_a(i),m_b(new int(j)){}

    B(const B & rval):
    m_a(rval.m_a),
    m_b(new int(*rval.m_b))
    {
    }
    A     m_a;
    int * m_b;
};

int main()
{
    B c(2,3); // a=2, *m_b=3
    B d(c);   //after copy constructor, a=2, *m_b=3
}