【发布时间】:2020-09-05 18:53:14
【问题描述】:
我尝试将指向抽象类 (list<shared_ptr<Base>> list_) 的智能指针列表包装到一些类 (Item、Drawer、Box) 中。然后在主函数中,我有一个Box'es 的map,但它不起作用。我找到了一种方法,我可以使用new,但我怀疑它只会导致我看不到的错误。如何让它发挥作用?代码如下:
#include <iostream>
#include <list>
#include <map>
#include <memory>
using namespace std;
class Base {
public:
virtual int get() = 0;
};
class Derived : public Base {
public:
Derived(int x) { x_ = x; }
int get() override { return x_; }
private:
int x_;
};
class Item {
public:
Item() {
for (int i = 1; i <= 10; i++) {
list_.push_back(make_shared<Derived>(i));
}
}
list<shared_ptr<Base>>& get_list() { return list_; }
private:
list<shared_ptr<Base>> list_;
};
class Drawer {
public:
Drawer(Item& item) : item_(item) {}
void Draw() {
list<shared_ptr<Base>>& list = item_.get_list();
cout << list.size() << ": ";
while (!list.empty()) {
shared_ptr<Base> pointer = dynamic_pointer_cast<Derived>(list.front());
cout << pointer->get() << " ";
list.pop_front();
}
cout << endl;
}
private:
Item& item_;
};
class Box {
public:
Box() : drawer_(item_) {}
void Draw() { drawer_.Draw(); }
private:
Item item_;
Drawer drawer_;
};
int main() {
Box box;
box.Draw();
map<int, Box> boxes; // it doesn't work, why?
for (int i = 0; i < 3; i++) {
boxes.insert(std::pair<int, Box>(i, Box()));
}
for (auto& b : boxes) { b.second.Draw(); }
map<int, Box*> pointers; // it does work, why?
for (int i = 0; i < 3; i++) {
pointers.insert(std::pair<int, Box*>(i, new Box()));
}
for (auto& b : pointers) { b.second->Draw(); }
for (auto& b : pointers) { delete b.second; }
}
结果如下:
10: 1 2 3 4 5 6 7 8 9 10
0:
0:
0:
10: 1 2 3 4 5 6 7 8 9 10
10: 1 2 3 4 5 6 7 8 9 10
10: 1 2 3 4 5 6 7 8 9 10
【问题讨论】:
-
地址消毒剂是你的朋友。它立即表明该程序正在做一些古怪的事情。
标签: c++ pointers polymorphism abstract-class smart-pointers