这样使用新的运算符是对的吗?

时间:2014-03-30 01:09:16

标签: c++ new-operator

int main()
{
    int* nir = new int; // creating dynamic memory
    *nir = 7; // assigning value
    cout << *nir << endl;
    delete nir; // deleting 
    nir = 0; // **is this line for assigning the address nir=0? 0 is also part of memory right? Why didn't we put NULL?
    *nir = 8; // **can i do like this and change the value, so that the output can be 8 now?
    cout << *nir << endl;
    delete nir;
    nir = 0;
    return 0;
}

这是我为了解new而创建的代码。但是,即使它被Code :: Blocks编译得很好,在运行时也崩溃了。我有两个问题,我已在评论部分提到过。

nir = 0;

是用于分配地址nir = 0的这一行吗? 0也是记忆的一部分吧?我们为什么不放nir = NULL

*nir = 8;

我可以这样做并更改值,以便输出现在可以8吗?毕竟,我已经删除了*nir值。

4 个答案:

答案 0 :(得分:0)

nir=0;

这将指针设置为NULL。在这种情况下,0和NULL是相同的。

*nir=8

这是错误的,因为nir不是有效的指针。崩溃并不令人惊讶!

cout<<*nir<<endl;

这也是错误的,因为nir是无效指针。你不能读或写。

delete nir;

这是无害的,因为删除NULL指针是安全的(它什么都不做)。

答案 1 :(得分:0)

此代码段错误

nir=0;     //**is this line for assigning the address nir=0? 0 is also part of memory right? Why didn't we put NULL?
*nir=8;    //**can i do like this and change the value, so that the output can be 8 now?
cout<<*nir<<endl;
delete nir;
nir=0;

您没有分配内存并且正在尝试写入地址0。

*nir=8;    //**can i do like this and change the value, so that the output can be 8 now?

通常程序会崩溃。

至于行

nir = 0;

然后它相当于

nir = NULL;

在C ++中,NULL通常定义为0或(long)0,依此类推。

根据C ++标准

  

1空指针常量是带有值的整数文字(2.14.2)   零或std :: nullptr_t类型的prvalue。空指针常量可以   被转换为指针类型;结果是空指针值   这种类型的,可以与对象的每个其他值区分开来   指针或函数指针类型。

答案 2 :(得分:0)

您标记了c ++,因此我建议使用nullptr而不是0 / NULL

nir = nullptr;

问题

The literal 0 (which is essentially of type int) also serves as a null pointer literal in C++. This kludge results in ambiguity and bugs.

解决方案

Use the nullptr keyword instead of 0 to indicate a null pointer value

source

答案 3 :(得分:0)

您故意犯下的错误的简短明细:

int main()
{
    int* nir = new int; // allocating dynamic memory
    *nir = 7; // assigning value
    cout << *nir << endl;
    delete nir; // deleting 
    nir = 0; // **is this line for assigning the address nir=0?
      // 0 is also part of memory right? Why didn't we put NULL?

之前的评论是错误的。由于历史原因,将文字0指定给指针变量意味着将其设置为空指针常量。这不能保证为0 [!!!]。 NULL和nullptr_t更现代......

    *nir = 8; // **can i do like this and change the value,
      // so that the output can be 8 now?
    cout << *nir << endl;

在某些系统上,您可以这样做。但是您的计算平台现在已经无可挽回地被破坏了。现代系统抓住了罪魁祸首并提出了一般保护错误,这只会导致你的计划失败。

    delete nir;

因为程序员热衷于避免无用的工作,所以上面的(删除NULL)被定义为no-op

    nir = 0;
    return 0;

前两行没用,因为nir永远不再使用,而main每个标准返回0,除非它明确没有,与其他任何函数形成鲜明对比。

}