为什么Java没有复制构造函数?

为什么Java没有复制构造函数?

问题描述:

为什么Java不支持像C ++中的复制构造函数?

Why doesn't Java support a copy constructor like in C++?

首先,复制构造函数就是这样:

Firstly, a copy constructor is nothing more than:

public class Blah {
  private int foo;

  public Blah() { } // public no-args constructor
  public Blah(Blah b) { foo = b.foo; }  // copy constructor
}



现在C ++将使用语句隐式调用复制构造函数像这样:

Now C++ will implicitly call the copy constructor with a statement like this:

Blah b2 = b1;

在该实例中的克隆/复制在Java中没有任何意义,因为所有b1和b2都是引用,值对象就像在C ++中。在C ++中,该语句生成对象状态的副本。在Java中,它只是复制引用。对象的状态不被复制,所以隐含地调用复制构造函数没有意义。

Cloning/copying in that instance simply makes no sense in Java because all b1 and b2 are references and not value objects like they are in C++. In C++ that statement makes a copy of the object's state. In Java it simply copies the reference. The object's state is not copied so implicitly calling the copy constructor makes no sense.

这真是真的。