struct Delete
{
template <typename T>
void operator() (T* t)
{
delete t;
}
};
template <typename Container>
class SmartContainer
: public Container
{
public:
~SmartContainer()
{
std::for_each(Container::begin(), Container::end(), Delete());
}
SmartContainer(const SmartContainer& other)
{
for (typename Container::const_iterator iter = other.begin(); iter != other.end(); ++iter) {
push_back(new typename Container::value_type(**iter));
}
}
SmartContainer() {}
};
在這段代碼中我試過實現一個智能容器。該容器包含指針。它在銷燬時刪除指針。問題在於寫作複製構造函數。它應該複製對象並在容器中放置副本指針。我在這push_back
行中收到錯誤,因爲Container::value_type
是指針類型,但它需要創建一個解除引用類型的對象。 std::remove_pointer
可能在這裏很有用,但我的編譯器不支持C++ 11。也許一個普通的智能指針容器是一個更好的選擇,但我需要解決這個問題。如何實現智能容器的複製構造?
它看起來對我? (到目前爲止)'** iter'你的'Container'類似乎是一個指針類型,所以'push_back'也是正確的。一個用法示例將有助於澄清事物(http://sscce.org) –
@LightnessRacesinOrbit Container :: value_type是T *,那麼'new Container :: value_type'將創建一個'T **'。 – dyp
@dyp:哦,對:) –