gpt4 book ai didi

java - C++ 与 Java : endless loop creating objects only crashes C++

转载 作者:IT老高 更新时间:2023-10-28 22:05:47 28 4
gpt4 key购买 nike

这是我的一本书中的一个问题(没有附加答案),我已经思考了几天了。答案仅仅是因为 C++ 代码最终会崩溃,因为它在每次迭代后都会创建一个垃圾内存单元吗?

Consider the following Java and C++ code fragments, parts of two versions of a GUI based application which collects user preferences and use them to assemble a command and its parameters. The method/function getUserCommandSpecification() returns a string representing the command code and its parameters. The returned string is used to build the required command which is then executed.

Assume the following:

(i) After the creation in the while loop of the Command object (referred by cmd in Java case or pointed by cmd in C++ case), the reference / pointer cmd to the generated object is no more referenced or used.

(ii) The application also defines a class Command along with its method/function execute().

a. Which of the two code versions, detailed below, will eventually crash.
b. Explain why a program version crashes while the other one is not crashing.

Java 代码

...
while (true) {
String commandSpecification = getUserCommandSpecification();
Command cmd = new Command(commandSpecification);
cmd.execute();
}
...

C++ 代码

...
while (true) {
string commandSpecification = getUserCommandSpecification();
Command* cmd = new Command(commandSpecification);
cmd -> execute();
}
...

最佳答案

是的,由于 new Command(...) 没有 delete,C++ 版本泄漏。当然,它可以很容易地进行不同的编码以避免这种情况:

...
while (true) {
string commandSpecification = getUserCommandSpecification();
Command cmd(commandSpecification);
cmd.execute();
}
...

...所以我不确定这个例子是否像他们想象的那样具有启发性。

关于java - C++ 与 Java : endless loop creating objects only crashes C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13338340/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com