这个动态分配有什么作用呢?

发布于 2024-08-23 07:26:05 字数 154 浏览 5 评论 0原文

今天,我发现可以用C++编写这样的代码并编译它:

int* ptr = new int(5, 6);

这样做的目的是什么?我当然知道动态 new int(5) 的事情,但在这里我迷路了。有什么线索吗?

Today, I found out that you can write such code in C++ and compile it:

int* ptr = new int(5, 6);

What is the purpose of this? I know of course the dynamic new int(5) thing, but here i'm lost. Any clues?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

似梦非梦 2024-08-30 07:26:06

只需这样做:

int* ptr = new int(6);

就逗号运算符而言,当您无法在没有它的情况下完成所需的任务时,请使用它。应用诸如以下的技巧是没有用的:

int* ptr = new int(5, 6);

Simply do this:

int* ptr = new int(6);

As far as comma operator is concerned, use it when you can't do the desired task without it. There is no use of applying tricks such as:

int* ptr = new int(5, 6);
故人如初 2024-08-30 07:26:05

您正在使用逗号运算符,它仅计算一个值(最右边的值)。

逗号运算符(,)用于
分隔两个或多个表达式
仅包含一个表达式
预计。当集合为
表达式必须被评估为
value,只有最右边的表达式
已考虑。

Source

指针指向的内存地址初始化为6多于。

You are using the comma operator, it evaluates to only one value (the rightmost).

The comma operator (,) is used to
separate two or more expressions that
are included where only one expression
is expected. When the set of
expressions has to be evaluated for a
value, only the rightmost expression
is considered.

Source

The memory address that the pointer is pointing to is initialized with a value of 6 above.

余生再见 2024-08-30 07:26:05

我的编译器 g++ 在尝试执行此操作时返回错误。

您在什么编译器或代码中看到了这个?

My compiler, g++, returns an error when attempting to do this.

What compiler or code did you see this in?

巷雨优美回忆 2024-08-30 07:26:05

我相信这是一个错误,意味着分配某种二维数组。但是在 C++ 中你不能这样做。该代码片段实际上可以编译,因为它使用了逗号运算符,该运算符返回最后一个表达式并忽略所有其他表达式的结果。这意味着该语句相当于:

int* ptr = new int(6);

I believe it is bug which meant to allocate some sort of 2D array. You can't do that in C++ however. The snippet actually compiles because it's utilizing the comma operator, which returns the last expression and ignores the results of all the others. This means that the statement is equivalent to:

int* ptr = new int(6);
寂寞清仓 2024-08-30 07:26:05

5 被忽略。这会在堆上分配一个 int 并将其初始化为 (5,6)。

由逗号运算符分隔的一组语句的结果是最后一条语句的值,因此 int 被初始化为 6

The 5 is ignored. this allocates an int on the heap and initializes it to (5,6).

the result of a set of statements separated by the comma operator is the value of the last statement, so the int is initialized to 6

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文