考虑这段代码:
#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()
吗?