这个动态分配有什么作用呢?
今天,我发现可以用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需这样做:
就逗号运算符而言,当您无法在没有它的情况下完成所需的任务时,请使用它。应用诸如以下的技巧是没有用的:
Simply do this:
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:
您正在使用逗号运算符,它仅计算一个值(最右边的值)。
Source
指针指向的内存地址初始化为6多于。
You are using the comma operator, it evaluates to only one value (the rightmost).
Source
The memory address that the pointer is pointing to is initialized with a value of 6 above.
我的编译器 g++ 在尝试执行此操作时返回错误。
您在什么编译器或代码中看到了这个?
My compiler, g++, returns an error when attempting to do this.
What compiler or code did you see this in?
我相信这是一个错误,意味着分配某种二维数组。但是在 C++ 中你不能这样做。该代码片段实际上可以编译,因为它使用了逗号运算符,该运算符返回最后一个表达式并忽略所有其他表达式的结果。这意味着该语句相当于:
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:
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