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

Is it possible to "add" to the default copy constructor?

本文关键字:复制 构造函数 默认 添加 是否      更新时间:2023-10-16

是否可以"add"到默认复制构造函数?

。对于这个类:

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

我想写

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

不含a(rvalue.a)部分。

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

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

不可能。但是,如果您希望减少大量"默认复制"字段的冗余代码,则可以通过中间继承实现:

struct A1 {int a1;int a2;//……int的;};struct A:public A1{int * b;(const一rhs): A1 (rhs)、b(新int (* (rhs.b))) {}};

你想做的事情是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
}