std :: make_shared()是否使用自定义分配器? [英] Does std::make_shared() use custom allocators?
问题描述
考虑此代码:
#include <memory>
#include <iostream>
class SomeClass {
public:
SomeClass() {
std::cout << "SomeClass()" << std::endl;
}
~SomeClass() {
std::cout << "~SomeClass()" << std::endl;
}
void* operator new(std::size_t size) {
std::cout << "Custom new" << std::endl;
return ::operator new(size);
}
void operator delete(void* ptr, std::size_t size) {
std::cout << "Custom delete" << std::endl;
::operator delete(ptr);
}
};
int main() {
std::shared_ptr<SomeClass> ptr1(new SomeClass);
std::cout << std::endl << "Another one..." << std::endl << std::endl;
std::shared_ptr<SomeClass> ptr2(std::make_shared<SomeClass>());
std::cout << std::endl << "Done!" << std::endl << std::endl;
}
此处是其输出:
Custom new
SomeClass()
Another one...
SomeClass()
Done!
~SomeClass()
~SomeClass()
Custom delete
很显然, std :: make_shared()
没有调用 new
运算符-它正在使用自定义分配器。这是 std :: make_shared()
的标准行为吗?
Clearly, std::make_shared()
didn't call the new
operator -- it's using a custom allocator. Is this the standard behavior for std::make_shared()
?
推荐答案
shared_ptr创建):
效果:分配适合于类型T的对象,并通过放置新表达式
:: new(pv)T(std :: forward< Args>(args)...)在该内存中构造一个对象。
这允许 make_shared
为对象和对象分配存储空间出于效率原因,在一次分配中共享指针本身(控制块)的数据结构。
This allows make_shared
to allocate the storage for both the object and the data structure for the shared pointer itself (the "control block") in a single allocation, for efficiency reasons.
您可以使用 std :: allocate_shared
如果要控制该存储分配。
You could use std::allocate_shared
if you want to control that storage allocation.
这篇关于std :: make_shared()是否使用自定义分配器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!