Java 和 C++ 在对象创建方面的主要区别是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3820178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:31:50  来源:igfitidea点击:

What is the main difference in object creation between Java and C++?

javac++objectcreation

提问by AndrejaKo

I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?"

我正在准备 Java 考试,之前考试的一个问题是:“Java 和 C++ 在对象创建方面的主要区别是什么?”

I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when constructor of one class calls a method of another class which isn't constructed yet and so on, but I can't find anything obvious. The answer is supposed to be one or two sentences, so I don't think that description of whole object creation process in Java is what they had in mind.

我想我知道对象创建的基础知识,例如如何调用构造函数,Java 中的初始化块做了什么,以及当一个类的构造函数调用另一个尚未构造的类的方法时会发生什么等等,但我可以没有发现任何明显的东西。答案应该是一两句话,所以我不认为Java中对整个对象创建过程的描述是他们想到的。

Any ideas?

有任何想法吗?

回答by Prasoon Saurav

What is the main difference in object creation between Java and C++?

Java 和 C++ 在对象创建方面的主要区别是什么?

Unlike Java, in C++ objects can also be created on the stack.

与 Java 不同,在 C++ 中对象也可以在堆栈上创建。

For example in C++ you can write

例如在 C++ 中,您可以编写

Class obj; //object created on the stack

In Java you can write

在 Java 中,您可以编写

Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object

回答by paercebal

In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):

除了其他出色的答案之外,还有一件非常重要的事情,通常会被忽略/忘记或误解(这解释了为什么我会在下面详细说明过程):

  • In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
  • In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)
  • 在 Java 中,方法是虚拟的,即使从构造函数调用(这可能会导致错误)
  • 在 C++ 中,从构造函数调用时,虚方法不是虚方法(这可能会导致误解)

What?

什么?

  • Let's imagine a Base class, with a virtual method foo().
  • Let's imagine a Derived class, inheriting from Base, who overrides the method foo()
  • 让我们想象一个带有虚拟方法 foo() 的基类。
  • 让我们想象一个从 Base 继承的 Derived 类,它覆盖了方法 foo()

The difference between C++ and Java is:

C++和Java的区别在于:

  • In Java, calling foo() from the Base class constructor will call Derived.foo()
  • In C++, calling foo() from the Base class constructor will call Base.foo()
  • 在 Java 中,从 Base 类构造函数调用 foo() 将调用 Derived.foo()
  • 在 C++ 中,从 Base 类构造函数调用 foo() 将调用 Base.foo()

Why?

为什么?

The "bugs" for each languages are different:

每种语言的“错误”是不同的:

  • In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.
  • 在 Java 中,调用构造函数中的任何方法都可能导致细微的错误,因为重写的虚方法可能会尝试访问在派生类中声明/初始化的变量。

Conceptually, the constructor's job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven't been initialized yet – a sure recipe for disaster.

Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml

从概念上讲,构造函数的工作是使对象存在(这不是一项普通的壮举)。在任何构造函数中,整个对象可能只是部分形成——您只能知道基类对象已被初始化,但您无法知道从您那里继承了哪些类。然而,动态绑定的方法调用会“向前”或“向外”进入继承层次结构。它调用派生类中的方法。如果在构造函数中执行此操作,则会调用一个方法,该方法可能会操作尚未初始化的成员——这肯定会导致灾难。

布鲁斯·埃克尔,http://www.codeguru.com/java/tij/tij0082.shtml

  • In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.
  • 在 C++ 中,必须记住 virtual 不会按预期工作,因为只会调用当前构造的类的方法。原因是为了避免访问数据成员甚至还不存在的方法。

During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.

Scott Meyers, http://www.artima.com/cppsource/nevercall.html

在基类构造期间,虚函数永远不会进入派生类。相反,对象的行为就好像它是基类型一样。通俗地说,在基类构造期间,虚函数不是。

斯科特迈耶斯,http://www.artima.com/cppsource/nevercall.html

回答by LumpN

Besides heap/stack issues I'd say: C++ constructors have initialization lists while Java uses assignment. See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6for details.

除了堆/堆栈问题,我想说的是:C++ 构造函数有初始化列表,而 Java 使用赋值。有关详细信息,请参阅http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

回答by ybungalobill

I would answer: C++ allows creating an object everywhere: on the heap, stack, member. Java forces you allocate objects on the heap, always.

我会回答:C++ 允许在任何地方创建对象:在堆、堆栈、成员上。Java 强制您在堆上分配对象,总是.

回答by Archimedix

In Java, the Java Virtual Machine (JVM) that executes Java code has tomight1log all objects being created (or references to them to be exact) so that the memory allocated for them can later be freed automatically by garbage collection when objects are not referenced any more.

在Java中,执行Java代码的Java虚拟机(JVM)具有威力1日志中创建的所有对象(他们或引用是精确的),以便为它们分配内存以后可以自动释放由垃圾收集时,对象不再引用。

EDIT:I'm not sure whether this can be attributed to object creation in the strict sense but it surely happens somewhen between creation and assignment to a variable, even without an explicit assignment (when you create an object without assigning it, the JVM has to auto-release it some time after that as there are no more references).

编辑:我不确定这是否可以归因于严格意义上的对象创建,但它肯定会在创建和分配给变量之间的某个时间发生,即使没有显式分配(当您创建一个对象而不分配它时,JVM 有一段时间后自动释放它,因为没有更多的引用)。

In C++, only objects created on the stack are released automatically (when they get out of scope) unless you use some mechanism that handles this for you.

在 C++ 中,只有在堆栈上创建的对象才会自动释放(当它们超出范围时),除非您使用某种机制为您处理此问题。

1: Depending on the JVM's implementation.

1:取决于JVM的实现。

回答by Sjoerd

There is one main designdifference between constructors in C++ and Java. Other differences follow from this design decision.

C++ 和 Java 中的构造函数之间有一个主要的设计差异。其他差异源于此设计决策。

The main difference is that the JVM first initializes all members to zero, before starting to execute any constructor. In C++, member initialization is part of the constructor.

主要区别在于 JVM 在开始执行任何构造函数之前首先将所有成员初始化为零。在 C++ 中,成员初始化是构造函数的一部分。

The result is that during execution of a base class constructor, in C++ the members of the derived class haven't been initialized yet! In Java, they have been zero-initialized.

结果是在执行基类构造函数时,在 C++ 中,派生类的成员还没有被初始化!在 Java 中,它们已被零初始化。

Hence the rule, which is explained in paercebal's answer, that virtual calls called from a constructor cannot descend into a derived class. Otherwise uninitialized members could be accessed.

因此,paercebal 的回答中解释了规则,即从构造函数调用的虚拟调用不能下降到派生类。否则可以访问未初始化的成员。

回答by Knubo

Assuming that c++ uses alloc() when the new call is made, then that might be what they are looking for. (I do not know C++, so here I can be very wrong)

假设 c++ 在进行新调用时使用 alloc() ,那么这可能就是他们正在寻找的。(我不懂 C++,所以这里我可能会非常错误)

Java's memory model allocates a chunk of memory when it needs it, and for each new it uses of this pre-allocated area. This means that a new in java is just setting a pointer to a memory segment and moving the free pointer while a new in C++ (granted it uses malloc in the background) will result in a system call.

Java 的内存模型在需要时分配一块内存,并且对于每个新内存,它使用这个预先分配的区域。这意味着 java 中的 new 只是设置一个指向内存段的指针并移动空闲指针,而 C++ 中的 new(允许它在后台使用 malloc)将导致系统调用。

This makes objects cheaper to create in Java than languages using malloc; at least when there is no initialization ocuring.

这使得在 Java 中创建对象比使用 malloc 的语言更便宜;至少在没有初始化 ocuring 时。

In short - creating objects in Java is cheap - don't worry about it unless you create loads of them.

简而言之——在 Java 中创建对象很便宜——除非你创建了大量的对象,否则不要担心。