我发现自定义分配器有时可以很简单地添加到程序中——例如,在某些特定情况下,只需替换文本 std::vector<int>
就足够了。与 std::vector<int, SomeAllocator>
并重新编译。
但是如果我想在直接使用 new
的代码中用自定义分配器表示的标准内存管理直接替换标准内存管理怎么办?和 delete
,像这样:
class Thingy
{
int whatever;
public:
Thingy(int whatever) : whatever(whatever) {}
};
Thingy* thingy = new Thingy(77);
delete thingy;
我是分配器的新手,但我想我可以通过调用四种分配器方法来实现这一点:一种用于分配,一种用于构造,一种用于销毁,一种用于解除分配。
SomeAllocatorForThingy a;
Thingy* thingy = a.allocate(1);
a.construct(thingy, 77);
a.destroy(thingy);
a.deallocate(thingy, 1);
或者类似的东西。但我宁愿用两个命令来完成,就像我可以使用 new
一样和 delete
;我想这样做而不必添加额外的 1
参数重复。
标准库是否已经提供了执行此操作的标准方法?像这样的东西:
Thingy* thingy = std::new_allocated_object<Thingy, SomeAllocatorForThingy>(77);
std::delete_allocated_object<SomeAllocatorForThingy>(thingy);
也许还有一些其他形式的有状态分配器。
我预计为此目的编写自己的函数不会有问题,但如果标准函数已经存在,那么我宁愿使用它们。
最佳答案
您可以覆盖 new
和 delete
运算符,如 here 所述和 here .然后您可以继续按原样使用 new
和 delete
,但您可以控制分配和释放。
例子:
class Foo
{
public:
Foo()
{
std::cout << "Constructor" << std::endl;
}
~Foo()
{
std::cout << "Destructor" << std::endl;
}
void *operator new(size_t size)
{
std::cout << "new(" << size << ")" << std::endl;
return malloc(size);
}
void operator delete(void *ptr)
{
std::cout << "delete(" << ptr << ")" << std::endl;
if(ptr)
free(ptr);
}
};
int main()
{
Foo *bar = new Foo();
delete bar;
return 0;
}
这将打印如下内容:
new(1)
Constructor
Destructor
delete(0x7fa72b6000a0)
关于c++ - 是否有一种简单、标准的方法通过分配器访问 "new"和 "delete"对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713134/