Почему Java не имеет конструктора копии?

Вы должны открыть свой сервис для внешнего мира следующим образом:

version: '3'
services:
  mongo:
    image: mongo
    volumes:
      - ~/data:/data/db
    restart: always
  adminmongo:
    image: mrvautin/adminmongo
    ports:
      - 1234:1234

Теперь вы можете получить доступ к своему adminmongo по http: // localhost: 1234 .

И вам не нужно использовать ссылки здесь. Так как compose создает сеть и объединяет все сервисы в файлах compose. Вы можете получить доступ к другим контейнерам с их сервисными именами.

67
задан T.J. Crowder 19 January 2019 в 14:05
поделиться

7 ответов

Java does. They're just not called implicitly like they are in C++ and I suspect that's your real question.

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
}

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

Blah b2 = b1;

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.

And that's all there is to it really.

132
ответ дан 24 November 2019 в 14:31
поделиться

From Bruce Eckel:

Why does [a copy constructor] work in C++ and not Java?

The copy constructor is a fundamental part of C++, since it automatically makes a local copy of an object. Yet the example above proves that it does not work for Java. Why? In Java everything that we manipulate is a handle, while in C++ you can have handle-like entities and you can also pass around the objects directly. That’s what the C++ copy constructor is for: when you want to take an object and pass it in by value, thus duplicating the object. So it works fine in C++, but you should keep in mind that this scheme fails in Java, so don’t use it.

(I recommend reading the entire page -- actually, start here instead.)

14
ответ дан 24 November 2019 в 14:31
поделиться

I think the answer to this is very interesting.

For one, I believe that in Java all objects are on the heap, and while you don't have pointers, you do have "References". References have copy symantics and java internally keeps track of reference counts so that its garbage collector knows whats safe to get rid of.

Since you only access objects through copyable references, the actual number of times you need to copy an object is greatly reduced (for example, in C++ just passing an object to a function (by value) results in new objects being copy constructed, in Java only the reference to the object is passed). The designers probably figured that clone() would be enough for the remaining uses.

10
ответ дан 24 November 2019 в 14:31
поделиться

Guess they figured you can just make a clone() method instead?

1
ответ дан 24 November 2019 в 14:31
поделиться

It kind of does. When shallow copies are okay you have [clone()](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#clone()) and when they aren't you have to implement a deep copy just like C++.

The only substantive difference is that it's a factory method rather than a constructor proper, but in terms of flexibility and testability that's probably a good thing.

0
ответ дан 24 November 2019 в 14:31
поделиться

Это всего лишь мое мнение (я уверен, что есть оправданный ответ)

Конструкторы копирования в C ++ в первую очередь полезны, когда вы отправляете или возвращаете экземпляры классов по значению, поскольку это когда конструктор копирования прозрачно активирован.

Поскольку в Java все возвращается по ссылке, а виртуальная машина ориентирована на динамическое размещение, действительно не было оправдания сложности конструктора копирования.

Кроме того, поскольку все делается по ссылке, разработчику часто приходится предоставлять свою собственную реализацию и принимать решение о том, как клонировать поля.

2
ответ дан 24 November 2019 в 14:31
поделиться

I'm not much of a C++ programmer, but I do seem to remember a rule about the "three amigos" - copy constructor, assignment operator, and destructor. If you have one, then you likely need all three.

So maybe without a destructor in the language, they didn't want to include a copy constructor? Just a guess.

0
ответ дан 24 November 2019 в 14:31
поделиться
Другие вопросы по тегам:

Похожие вопросы: