创建一个易于维护的复制构造函数 [英] Creating an easy to maintain copy constructor

查看:172
本文介绍了创建一个易于维护的复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的类:

class A {

char *p;
int a, b, c, d;

public:
   A(const &A);
};

注意,我必须定义一个复制构造函数,这有两个问题:

Note that I have to define a copy constructor in order to do a deep copy of "p". This has two issues:


  1. 大多数字段应该被复制。

  1. Most of the fields should simply be copied. Copying them one by one is ugly and error prone.

更重要的是,每当一个新的属性被添加到类中,拷贝构造函数需要被更新,

More importantly, whenever a new attribute is added to the class, the copy constructor needs to be updated, which creates a maintenance nightmare.

我个人喜欢做:

A(const A &a) : A(a)
{
   // do deep copy of p
   :::
}



因此,首先调用默认的拷贝构造函数,执行。

不幸的是,这似乎不工作。

So the default copy constructor is called first and then the deep copy is performed.
Unfortunately this doesn't seem to work.

有更好的方法吗?
一个限制 - 我不能使用共享/智能指针。

Is there any better way to do this? One restriction - I can't use shared/smart pointers.

Sbi的建议很有道理。我想我将创建包装类来处理资源。我不想使用shared_ptr,因为boost库可能不是在所有平台上都可用(至少不是在标准分发版本中,OpenSolaris是一个例子)。

Sbi's suggestions make a lot of sense. I think I'll go with creating wrapper classes for handling the resource. I don't want to user shared_ptr since boost libraries may not be available on all platforms (at least not in standard distributions, OpenSolaris is an example).

如果你能让编译器为你创建默认的构造函数/赋值运算符,那么这将是巨大的,你可以只是添加你的功能。手动创建的复制构造函数/赋值运算符函数我认为将是一个麻烦创建和噩梦维护。所以我个人的经验法则是尽可能避免使用自定义副本构造函数/赋值运算符。

I still think it would have been great if you could somehow make the compiler to create the default constructor/assignment operators for you and you could just add your functionality on top of it. The manually created copy constructor/assignment operator functions I think will be a hassle to create and a nightmare to maintain. So my personal rule of thumb would be to avoid custom copy constructors/assignment operators at all cost.

感谢大家的回复和有用的信息, 。

Thanks everybody for their responses and helpful information and sorry about typos in my question. I was typing it from my phone.

推荐答案

根据经验:如果您必须手动管理资源,

As a rule of thumb: If you have to manually manage resources, wrap each into its own object.

char * 使用正确的复制构造函数将其转换为自己的对象,并让编译器为 A 执行复制构造函数。 请注意,这还涉及您尚未在您的问题中提到但仍需要处理的分配和销毁

标准库有几种类型可以选择,其中 std :: string std :: vector< char>

Put that char* into its own object with a proper copy constructor and let the compiler do the copy constructor for A. Note that this also deals with assignment and destruction, which you haven't mentioned in your question, but need to be dealt with nevertheless.
The standard library has several types to pick from for that, among them std::string and std::vector<char>.

这篇关于创建一个易于维护的复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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