为什么新的int()像c++中的数组一样工作?

发布于 2025-01-27 13:11:30 字数 279 浏览 5 评论 0 原文

据我所知,

int* p = new int();

就像用构造函数创建int一样。如果是这样,为什么以下代码像数组一样工作?

int* p = new int();
    
*p = 5;
    
p[1] = 15;
    
for (int i = 0; i < 2; i++)
    cout << p[i] << endl;
5
15

As far as I understand

int* p = new int();

Is something like creating an int with a constructor. If so why does the following code work like an array?

int* p = new int();
    
*p = 5;
    
p[1] = 15;
    
for (int i = 0; i < 2; i++)
    cout << p[i] << endl;
5
15

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

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

发布评论

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

评论(2

青巷忧颜 2025-02-03 13:11:30

为什么新的int()像c ++?

中的数组一样工作

为什么新的int()像c ++? p [1] 施加了访问存储在指向的内存位置的值的指针,该符号类似于数组符号,它是允许的,并且优先于指针表示法,因为它更可读取。


据我了解,

  int* p = new int();
 

就像用构造函数创建 int

一个 int 并将内存地址分配给指针 p

请注意,它可以是 int* p = new Int [2] ,它是完全相同的指针,但是在这种情况下,由 new> new 返回的内存块适用于2 <代码> int 而不仅仅是一个,顺便说一句,这将使您的代码的其余部分有效,除了您不 delete new 分配的内存,这会导致内存泄漏。

现在考虑以下代码:

int arr[10];
int* p = arr;

在这种情况下,您的指针完全相同,但它将指向具有自动存储持续时间的数组的第一个元素。

指针不知道它指出了多少内存,因为它指向给定内存块中的第一个元素,因为程序并不明显该块有多大。在索引指针时,不超越该内存的是程序员的责任。

要注意的一件重要的事情是,在某些情况下,其他语言可能会阻止您踩踏它,C ++没有,它信任程序员制作正确的代码,这就是为什么通常很难成为C ++程序员的原因。


正如已经指出的那样,您的程序在。注意链接资源的第一个短语,它简单地指出:

[未定义的行为] 如果违反该语言的某些规则

,则使整个程序毫无意义

情况,那么您所访问的内存就毫无意义,而您所访问的内存位于手动内存分配所定义的界限之外。输出是您期望的事实是(不好,我会说)运气,它可能会在今天输出正确的结果并明天崩溃,谁知道。

您可以通过上面的示例看到这种情况很难诊断,这是3个样本案例完全相同的类型。

无论如何,有一些方法可以诊断出这种记忆问题,例如 valgrind GCC地址消毒剂等。


附带说明,避免使用原始指针,请使用智能指针或一个 c ++容器如果可能的话。

我还鼓励您获得有关

Why does new int() work like an array in C++?

p[1] is equivalent to *(p + 1), it simply dereferences the pointer to access the value stored in the memory location where it points to, the notation is similar to array notation, it's allowed and is preferred to pointer notation because it's more readable.


As far as I understand

 int* p = new int();

Is something like creating an int with a constructor.

Yes, but that's not all, you are also allocating memory for exactly one int and assigning the memory address to the pointer p.

Note that it could be int* p = new int[2], it's the exact same pointer, but in this case the memory block returned by new is good for 2 int instead of just the one, incidentally this would make the rest of your code valid, except for the fact that you do not delete the memory allocated by new, which would cause a memory leak.

Now consider the following code:

int arr[10];
int* p = arr;

In this case you have the exact same pointer, but it will be pointing to the first element of an array with automatic storage duration.

The pointer does not know how much memory it points to because it's pointing to the first element in a given memory block, for the program it's not apparent how big that block is. When indexing the pointer, it's the programmer responsability to not overrun that memory.

One important thing to note is that, in some cases, where other languages might stop you from putting your foot in it, C++ does not, it trusts the programmer to produce correct code, that's why it's usually harder to be a C++ programmer.


As already pointed out your program incurs in undefined behavior while accessing p[1]. Note the first phrase of the linked resource, it simply states:

[Undefined behavior] renders the entire program meaningless if certain rules of the language are violated

That is the case here, the memory you are accessing is located out of the bounds defined by your manual memory allocation. The fact that the output is what you expect is a matter of (bad, I would say) luck, it may output the correct result today and crash tomorrow, who knows.

You can see by the above examples that this situation would be hard to diagnose, it's the exact same type for the 3 sample cases.

In any case there are ways to diagnose memory problems like this, examples are valgrind and gcc address sanitizer, among others.


On a side note, avoid using raw pointers, use smart pointers or one of the C++ containers if possible.

I would also encourage you to acquire some knowledge on the related topic of OOP RAII principles.

各自安好 2025-02-03 13:11:30

为什么以下代码像数组一样工作?

不是。该程序具有未定义的行为意味着它仍然存在错误,即使它没有明确说明并且“似乎正在起作用”。这是由于您的程序中使用了表达式 p [1] p [i]

未定义的行为意味着任何事情 1 可能发生,包括但不限于 提供了预期的输出。但是,永远不要依靠(或基于结论),这是基于具有不确定行为的程序的输出。该程序可能只是崩溃。

因此,您看到的(也许看到)的输出是不确定行为的结果。正如我所说,不依赖具有UB程序的程序的输出。该程序可能只是崩溃。

因此,使程序正确的第一步是删除UB。 然后,只有这样,您才能开始对程序的输出进行推理。


1 有关未定义行为的更精确的定义,请参见 提到的地方:对程序的行为没有任何限制

why does the following code work like an array?

It doesn't. The program has undefined behavior meaning it is still in error even if it doesn't say so explicitly and "seems to be working". This is due to the use of the expressions p[1] and p[i] in your program.

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

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