我使用的是 Windows,x64 模式。在 Visual Studio 上使用 MSVC 编译。这new
当我这样做时,运算符似乎没有按预期工作:
char* buf = new char[1LLU << 32];
但是如果我传入一个变量而不是直接输入大小,它就可以正常工作:
uint64_t sz = 1LLU << 32;
char* buf = new char[sz];
查看汇编代码,编译器忽略了我提供的大小,只是xor ecx, ecx
我相信这只是将 0 传递给new
操作员。
这实在令人费解!标准中是否指定了一些我不知道的规则?
p.s. char* buf = new char[1LLU << 31];
工作没有问题。所以我认为这与我正在使用的整数的大小有关。但在文档中,new
接受一个size_t
作为参数,在 x64 上应该是uint64_t
.
VirtualAlloc()
/HeapAlloc()
是很好的替代品,使用起来比new
在此背景下。
完整代码(注意*尝试在 Visual Studio 中本地重现此代码):
#include <iostream>
#include <cstdint>
int main()
{
char* ptr = new char[1LLU << 32];
memset(ptr, 0, sizeof(char) * (1LLU << 32)); //Access violation writing location...
}
#include <iostream>
#include <cstdint>
int main()
{
uint64_t sz = 1LLU << 32;
char* ptr = new char[sz];
memset(ptr, 0, sizeof(char) * (1LLU << 32)); //no problem
}