new 不分配内存
new does not allocate memory
这应该每秒用大约 100 MB 填满我的内存。我使用 gnome-systemmonitor 和 htop 跟踪内存使用情况。但不知何故它没有。为什么?
#include "unistd.h"
#include <iostream>
int main(int argc, char *argv[])
{
while (true){
std::cout << "New one" << std::endl;
new char[100000000];
sleep(1);
}
return 0;
}
至运行:
g++ -std=c++11 -O0 main.cpp; ./a.out
因为您没有使用它,Linux 进行延迟分配,因此在您使用它之前它不会实际映射任何内存页。
如果你输入一些代码:
char* test = new char[100000000];
test[0] = 'a';
test[4096] = 'b';
...
您应该看到它实际上正在消耗您的系统内存。
我只见过 clang optimize away calls to new,一般情况下,当您使用 -O0
时,编译器不会执行如此积极的优化。
我们可以从 godbolt 中看出 gcc
确实没有优化掉对 new
的调用,代码非常相似:
.L2:
movl 0000000, %edi
call operator new[](unsigned long)
movl , %edi
call sleep
jmp .L2
所以很可能 并且涉及延迟分配,因此一旦您写入分配的内存,您就会看到它正在被使用。
这应该每秒用大约 100 MB 填满我的内存。我使用 gnome-systemmonitor 和 htop 跟踪内存使用情况。但不知何故它没有。为什么?
#include "unistd.h"
#include <iostream>
int main(int argc, char *argv[])
{
while (true){
std::cout << "New one" << std::endl;
new char[100000000];
sleep(1);
}
return 0;
}
至运行:
g++ -std=c++11 -O0 main.cpp; ./a.out
因为您没有使用它,Linux 进行延迟分配,因此在您使用它之前它不会实际映射任何内存页。
如果你输入一些代码:
char* test = new char[100000000];
test[0] = 'a';
test[4096] = 'b';
...
您应该看到它实际上正在消耗您的系统内存。
我只见过 clang optimize away calls to new,一般情况下,当您使用 -O0
时,编译器不会执行如此积极的优化。
我们可以从 godbolt 中看出 gcc
确实没有优化掉对 new
的调用,代码非常相似:
.L2:
movl 0000000, %edi
call operator new[](unsigned long)
movl , %edi
call sleep
jmp .L2
所以很可能