是否可以"添加"到默认复制构造函数?
Is it possible to "add" to the default copy constructor?
是否可以"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
}
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 复制构造函数、赋值运算符C++
- std::ofstream 作为类成员删除复制构造函数?
- 复制构造函数C++无法正确复制指针
- 关于复制构造函数的一个棘手问题
- 为什么调用复制构造函数而不是移动构造函数?
- 填充上编译器生成的复制构造函数之间的不一致
- C++ 对象指针数组的复制构造函数
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 防止在复制构造函数中隐式调用基构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 具有已删除移动和复制构造函数的类的就地构造
- 复制构造函数隐式转换问题
- 复制构造函数中的递归调用