gpt4 book ai didi

c++ - 其中 ( new int*) 指向

转载 作者:行者123 更新时间:2023-11-28 07:10:19 26 4
gpt4 key购买 nike

我在 vs2012 中用下面的代码做了一些测试:

在 Debug模式下:

int *b; int *a = b;   //  Crash!!
int *b = *(new int*); int *a = b; //this is ok

我很好奇为什么会这样。默认情况下 (new int*) 是否指向一些实际内存?而且由于它是在非 Debug模式下运行的,所以我想知道是否可以编写这样的代码

最佳答案

I'm curious why it's like this.

由于使用未初始化对象的值,两者都有未定义的行为。虽然这会崩溃令人惊讶,但没有理由假设它不会以某种不可预测的方式出错。

取消引用未初始化的指针(例如 int a = *b; 而不是 int *a = b;),更有可能导致崩溃。你确定你没有那样做吗?

Does the (new int*) points to some real memory by default?

new int* 返回的int** 可以。它指向的 int* 是未初始化的。

if it is ok to write such code

编写具有未定义行为的代码永远是不对的。即使它看起来“有效”,它也会在您最意想不到的时候反咬一口。

关于c++ - 其中 ( new int*) 指向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21089016/

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