C++ 在空指针上使用 new

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14111900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:59:44  来源:igfitidea点击:

Using new on void pointer

c++

提问by Brandon

int main()
{
    void* Foo = new???
    delete Foo;
}

How do you do something like the above? You can't put new void[size]. And I don't want to know how to do it with malloc()and free(). I already know that works. I'm curious and want to know how it's done with new and delete.

你如何做类似上面的事情?你不能放new void[size]。我不想知道如何用malloc()and来做free()。我已经知道那行得通。我很好奇,想知道 new 和 delete 是如何完成的。

I googled this and saw something about operator new(size); and operator delete(size);

我用谷歌搜索了这个,看到了一些关于operator new(size); 和operator delete(size);

What is the difference between those and new/ delete? Why does C++ not just allow new void* [size]?

这些和new/ 有delete什么区别?为什么 C++ 不仅仅允许 new void* [size]

回答by ybungalobill

This will do the trick:

这将解决问题:

int main()
{
    void* Foo = ::operator new(N);
    ::operator delete(Foo);
}

These operators allocate/deallocate raw memory measured in bytes, just like malloc.

这些运算符分配/释放以字节为单位的原始内存,就像malloc.

回答by Oliver Charlesworth

Why does C++ not just allow new void[size]?

为什么 C++ 不仅仅允许 new void[size]?

Because voidis not an object; it has no size! How much space should be allocated? Bear in mind that new T[size]is approximatelyequivalent to malloc(sizeof(T) * size).

因为void不是对象;它没有大小!应该分配多少空间?记住,new T[size]大致等同于malloc(sizeof(T) * size)

If you just want a raw byte array, then you could use char.*

如果您只想要一个原始字节数组,那么您可以使用char. *



* Although, of course, because this is C++ you should use something like std::vector<char>to avoid memory-leak and exception-safety issues.* 当然,因为这是 C++,所以你应该使用类似的东西std::vector<char>来避免内存泄漏和异常安全问题。

回答by Dietmar Kühl

C++ travels in constructed objects allocated using some variation of new T. or new T[n]for some type T. If you really need uninitialized memory (it is very rare that you do), you can allocate/deallocate it using operator new()and operator delete():

C++ 在使用new T. 或new T[n]对于某些类型T。如果你真的需要未初始化的内存(你很少这样做),你可以使用operator new()and分配/取消分配它operator delete()

void* ptr = operator new(size);
operator delete(ptr);

(similarily for the array forms)

(类似于数组形式)

回答by 0x499602D2

void *is convertible to any pointer type. You can simply do void *Foo = new intor any other type that you want. But there really isn't a reason to do this in C++.

void *可转换为任何指针类型。你可以简单地做void *Foo = new int或任何其他你想要的类型。但是真的没有理由在 C++ 中这样做。

回答by my_username

You could do

你可以做

void* data = new char[num_of_bytes];

to allocate some memory, in a similar fashion as malloc

以类似于 malloc 的方式分配一些内存