使用新的空指针 [英] Using new on void pointer

查看:49
本文介绍了使用新的空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

您如何执行上述操作?您不能放置 new void [size] .而且我不想知道如何使用 malloc() free()来做到这一点.我已经知道这可行.我很好奇,想知道如何使用new和delete进行操作.

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.

我在Google上搜索了一下,并看到了有关 operator new(size)的一些信息;和 operator delete(size);

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

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

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

推荐答案

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

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

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

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

如果只需要原始字节数组,则可以使用 char . *

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


*当然,由于这是C ++,因此应使用类似 std :: vector< char> 之类的东西,以避免内存泄漏和异常安全问题.


* Although, of course, because this is C++ you should use something like std::vector<char> to avoid memory-leak and exception-safety issues.

这篇关于使用新的空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆