考慮this code:std :: make_shared()使用自定義分配器嗎?
#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()
的標準行爲嗎?
'std :: allocate_shared(const A&,Args && ...)'也值得一提。第一個參數是調用'A :: allocate'的分配器。 –