C++:行为类似于 calloc 的新调用?
我可以像 calloc
一样调用 new
来将内存清零吗?
Is there a call I can make to new
to have it zero out memory like calloc
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(11)
贱人配狗天长地久2024-07-26 02:47:42
不,但创建一个像 calloc 一样的新版本相当容易。 它的实现方式与 new 的无抛出版本的实现方式大致相同。
SomeFile.h
struct zeromemory_t{};
extern const zeromemory_t zeromemory;
void* __cdcel operator new(size_t cbSize, const zeromemory_t&);
SomeFile.cpp
const zeromemory_t zeromemory;
void* _cdecl operator new(size_t cbSize, const zeromemory_t&)
{
void *mem = ::operator new(cbSize);
memset(mem,0,cbSize);
return mem;
}
现在您可以执行以下操作来获取内存为零的 new
MyType* pMyType = new (zeromemory) MyType();
另外,您还需要做其他有趣的事情,例如定义 new[] ,这也相当简单。
北方的韩爷2024-07-26 02:47:42
您可以对运算符 new 进行全局重载,并让它从 calloc() 中获取原始内存。 这样,在构造函数运行之前内存就会被擦除,因此不会出现任何问题。
任何自行重写 new 的类都不会获得基于 calloc()
的特殊 new
,但该类无论如何都应该正确初始化自身。
不要忘记覆盖 new
和 delete
以及数组版本...
类似于:
#include <exception> // for std::bad_alloc
#include <new>
#include <stdlib.h> // for calloc() and free()
void* operator new (size_t size)
{
void *p=calloc(size, 1);
if (p==0) // did allocation succeed?
throw std::bad_alloc();
return p;
}
void operator delete (void *p)
{
free(p);
}
void* operator new[] (size_t size)
{
void *p=calloc(size, 1);
if (p==0) // did allocation succeed?
throw std::bad_alloc();
return p;
}
void operator delete[] (void *p)
{
free(p);
}
请注意,这些简单版本并不完全符合它们应有的样子 - new
运算符应在调用 new_handler
(如果已安装)的循环中运行,并且仅在没有 时抛出
。 或者类似的事情,我得查一下并稍后更新。bad_alloc
异常new_handler
哦,您可能还想覆盖 no_throw
版本。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
与一些人的回答相反,这是可能的。
将对所有字符进行零初始化(实际上,这称为值初始化。但值初始化将对标量类型数组的所有成员进行零初始化)。 如果这就是你所追求的。
值得注意的是,它也适用于没有用户声明构造函数的类类型(数组),在这种情况下,它们的任何成员都被值初始化:
它不是某种扩展或其他东西。 它在 C++98 中的工作方式和行为方式也相同。 就在那里,它被称为默认初始化而不是值初始化。 然而,在这两种情况下,对于标量或标量数组或 POD 类型都会进行零初始化。
Contrary what some are saying in their answers, it is possible.
Will zero initialize all the characters (in reality, it's called value-initialization. But value-initialization is going to be zero-initialization for all its members of an array of scalar type). If that's what you are after.
Worth to note that it does also work for (arrays of) class-types without user declared constructor in which case any member of them is value initialized:
It's not some extension or something. It worked and behaved the same way in C++98 too. Just there it was called default initialization instead of value initialization. Zero initialization, however, is done in both cases for scalars or arrays of scalar or POD types.