对象生命周期
用 new 创建的对象存在于 C++ 中。它的句柄不再被使用后,垃圾回收器会释放它;delete() 则会立即释放它。
Block 会给自己计数:构造函数加一,析构函数减一。执行 await first.delete() 后,计数立即下降,first 也不能再使用。second 则在垃圾回收器回收它时才会消失。
垃圾回收器只考虑 JavaScript 中那个很小的句柄,而不考虑它背后的内存。对于占用大量内存或持有文件等资源的对象,以及在循环中创建的对象,请调用 delete()。
试一试
在循环中创建十个块并打印计数,然后在循环内删除每个块,再打印一次。[■]native.h1#pragma once
// Each Block counts itself in and out, so JavaScript can see
// when C++ frees one.
class Block {
public:
explicit Block(int megabytes);
~Block();
int megabytes() const;
static int alive();
private:
int size;
};
[■]main.js2import { initNative, Block } from './native/native.h';
await initNative();
const first = await new Block(64);
const second = await new Block(8);
console.log('alive:', await Block.alive());
await first.delete();
console.log('after delete:', await Block.alive());
console.log('still there:', await second.megabytes(), 'MB');