如何覆蓋STL中allocator類中構造方法的默認行爲?以下似乎不工作:如何覆蓋C++中allocator類中構造方法的默認行爲STL
#include <list>
#include <iostream>
#include <memory>
struct MyObj {
MyObj() {
std::cout << "This is the constructor" << std::endl;
}
MyObj(const MyObj& x) {
std::cout << "This is the copy constructor" << std::endl;
}
};
class MyAlloc : public std::allocator <MyObj>{
public:
void construct(pointer p, const_reference t){
std::cout << "Construct in the allocator" << std::endl;
new((void*)p) MyObj(t);
}
};
int main(){
MyObj x;
std::list <MyObj,MyAlloc> list(5,x);
}
該程序返回
This is the constructor
This is the copy constructor
This is the copy constructor
This is the copy constructor
This is the copy constructor
This is the copy constructor
我想它
This is the constructor
Construct in the allocator
This is the copy constructor
Construct in the allocator
This is the copy constructor
Construct in the allocator
This is the copy constructor
Construct in the allocator
This is the copy constructor
Construct in the allocator
This is the copy constructor
+1。非常好!... – Nawaz
所以@NicolBolas說'不從'std :: allocator'派生',但@Nawaz'的答案正是如此。這是一個有效的,受支持的事情嗎?或者如果我嘗試它,宇宙理論上可以變成豆芽味的果凍嗎? 忽略該虛擬分派不可用(因爲當提供派生類型作爲模板參數時,基類型是非實質性的且不需要虛擬分派)並且忽略派生的設計優點作爲繼承實現的機制。 – boycy