开发者

Is this a valid Copy Ctor ?

I wonder if there is something wrong with the copy constructor function below?

class A
{
   pri开发者_高级运维vate:
      int m;
   public:
      A(A a){m=a.m}
}


Two things:

  • Copy constructors must take references as parameters, otherwise they are infinitely recursive (in fact the language won't allow you to declare such constructors)

  • It doesn't do anything the default copy ctor doesn't do, but does it badly - you should use initialisation lists in a copy ctor wherever possible. And if the default copy ctor does what you want, don't be tempted to write a version yourself - you will probably only get it wrong, and you will need to maintain it.


There 3 problems.

First, you have forgot ";" at the end of the m=a.m so your code would not compile.

Second, passing by reference is preferred in most cases where you pass something with size greater than size of a register on your platform.

Third, since you are not going to change the source object, it is better to have it with const. So, finally this is what we have:

A(const A & a) : m(a.m) {}


The problem is that the copy constructor is called for parameter passed by value. So you have to pass the parameter of the copy constructor by reference (usually const reference) if you don't want a non terminating recursion. A minor issue is that you aren't using the initialization list, which is preferable to initialize the member. Fixing both issues:

A(A const& a)
  : m(a.m)
{}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜