Is it possible to "add" to the default copy constructor?
Is it possible to "add" to the default copy constructor?
Eg. For this class:
class A
{
public:
int a;
int* b;
};
I want to just write
A::A(const A& rvalue):
a(rvalue.a),
b(new int(*(rvalue.b)))
{}
without the a(rvalue.a)
part开发者_开发技巧.
(Ignore the bad/ugly code and possible memory leaks)
What you ask for is impossible. Once you declare your own copy constructor the compiler will not generate a copy constructor for you. That means you won't be able to simply add or augment the default copy constructor because it won't exist. It's all or nothing, so to speak.
it is impossible. However, if you want to reduce redundant code for a large number of "default copied" fields, it may be achieved with intermdiate inheritance:
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))) {} };
What you want to do is not nartually supported by C++ : you cannot have half default constructor.
But what you want to achieve can be done by the little trick below:
please note this small demo below have a lot defects(memory leak etc), so it's ONLY for demostration the tentative solution only:
//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
}
精彩评论