gpt4 book ai didi

c++ - 动态内存分配,堆,间接,NULL

转载 作者:行者123 更新时间:2023-11-28 07:02:27 25 4
gpt4 key购买 nike

我试图保证我动态分配的内存没有指向任何地方。

我尝试了以下方法

template<typename T>
[...something here...]
T *mem = new T[size];

for ( int i=0; i<size; i++ )
{
(mem+i) = NULL;
}
[...something else there...]

就像一个人会写

int *pInt = new int;
pInt = NULL;

但这行不通,因为在上面的示例中 mem 不是“左值”?

为什么只有当我在堆上动态分配更多特定类型的内存时才会出现这种情况?

此外,如果我使用模板函数,还会发生一件奇怪的事情,因为这样写似乎是合法的

template<typename T>
[...something here...]
T mem = new T[size];

for ( int i=0; i<size; i++ )
{
*(mem+i) = NULL;

/* or the equivalent
mem[i] = NULL;
*/
}
[...something else there...]

如何将 NULL(基本上是 int 值 0)分配给基本上可以是任何东西的变量或对象?它可能是一个 int 变量,很好,它可以工作。但是,如果我用 std::string 调用模板函数会怎样。它根本不应该工作,对吧?那么为什么写这样的东西看起来是合法的呢?

是编写泛型的自由,还是注意的责任,不要调用错误类型的泛型函数?

最佳答案

But it that doesn't work because in the upper example "mem" isn't an "lvalue"?

确实,您正在尝试重新分配临时指针mem+i;那没有意义。据推测,您想将数组成员 (mem[i]*(mem+i)) 设置为某个值;尽管可能不会 NULL 除非 T 应该是指针类型。

在单个对象的示例中,您将唯一的指针重新分配给已分配的对象;因此您无法使用或删除该对象。

How can it be possible to assign NULL ( wich is basically the int value 0 ) to an variable or object that could be basically anything?

因为,在 C++11 之前,唯一有效的空指针常量(因此 NULL 宏的唯一有效扩展)是零值整数常量;所以代码扩展成类似

*(mem+i) = 0;

这对许多类型都有效。如今,NULL 可能(也可能不会)扩展为 nullptr,在这种情况下,它只对指针类型有效。

But what if i called the template function with std::string. It shouldn't work at all, right ?

std::string 有一个构造函数和赋值运算符接受一个指向 C 风格字符串的指针,例如允许

std::string hello = "Hello, world!";

这些也可以采用空指针,给出未定义的行为。

关于c++ - 动态内存分配,堆,间接,NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22233759/

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