【问题标题】:How to implement copy construcuctor of smart container?如何实现智能容器的拷贝构造函数?
【发布时间】:2014-02-10 01:20:21
【问题描述】:
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 也是正确的。一个使用示例将有助于澄清事情 (sscce.org)
  • @LightnessRacesinOrbit Container::value_typeT*,然后new Container::value_type 将创建一个T**
  • @dyp:哦,对了 :) 两个都加 1

标签: c++ pointers copy-constructor smart-pointers


【解决方案1】:

更改模板参数。而不是Container 改为Container&lt;T*&gt;,那么您将拥有可用的基础对象类型。

template <typename Container, typename T>
class SmartContainer
     : public Container<T*>

【讨论】:

  • 我不确定你的意思。部分专业化?
  • @dyp,抱歉我不是很清楚。我添加了一个示例。
  • 在这种情况下,Container 需要是模板模板参数,template &lt; template&lt;class...&gt; class Container, class T, class... Add &gt; class SmartContainer : public Container&lt;T*, Add...&gt;(分配器等可以放入Add 参数包中)
【解决方案2】:

您可以实现自己的remove_pointer(来自cppreference.com):

template< class T > struct remove_pointer                    {typedef T type;};
template< class T > struct remove_pointer<T*>                {typedef T type;};
template< class T > struct remove_pointer<T* const>          {typedef T type;};
template< class T > struct remove_pointer<T* volatile>       {typedef T type;};
template< class T > struct remove_pointer<T* const volatile> {typedef T type;};

然后typename remove_pointer&lt;Container::value_type&gt;::type

【讨论】:

  • 我认为你在Container::value_type之前仍然需要一个typename
猜你喜欢
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多