【问题标题】:transform iterator with map of unique_ptr使用 unique_ptr 映射变换迭代器
【发布时间】:2013-06-04 09:23:46
【问题描述】:

我有一个Holder 类,它应该只公开其映射的值。我使用了一个变换迭代器来做到这一点。如果我使用指向类型 (ClassA*) 的普通指针而不是使用 unique_ptr,它会起作用。我将以下示例基于此代码: transform_iterator compile problem

我收到以下错误(源自 begin() 函数),这让我认为有人试图复制这对而不是使用引用。

提前致谢

错误 C2248:
'std::unique_ptr<ClassA,std::default_delete<_Ty>>::unique_ptr' :
无法访问类中声明的私有成员
'std::unique_ptr<ClassA,std::default_delete<_Ty>>'

#include <iostream>
#include <map>
#include <functional>
#include <memory>
#include <string>
#include <boost/iterator/transform_iterator.hpp>

struct ClassA
{
    ClassA( const std::string& strName ) : m_strName( strName ) {}
    std::string m_strName;
};

template <typename K, typename V>
const V & get_value(std::pair<K, V> const & p)  { return p.second; }

class Holder
{
    typedef std::map<int, std::unique_ptr< ClassA > > TMap;
    typedef std::unique_ptr< ClassA > UniqueA;
    TMap m_Map;
public:
    Holder()
    {
        UniqueA a( new ClassA( "#2# ") );
        UniqueA b( new ClassA( "#3# ") );
        UniqueA c( new ClassA( "#4# ") );
        m_Map.insert( std::make_pair( 2, std::move( a ) ) );
        m_Map.insert( std::make_pair( 3, std::move( b ) ) );
        m_Map.insert( std::make_pair( 4, std::move( c ) ) );
    }
    typedef std::function< const TMap::mapped_type & (const TMap::value_type &) > F;
    typedef boost::transform_iterator<F, TMap::iterator> transform_iterator;

    transform_iterator begin()
    {
        return boost::make_transform_iterator(m_Map.begin(), &get_value< int, std::unique_ptr< ClassA > >);
    }
    transform_iterator end()
    {
        return boost::make_transform_iterator(m_Map.end(), &get_value< int, std::unique_ptr< ClassA > >);
    }
};

void MyTest()
{
    Holder bla;
    auto s_beg = bla.begin();
    auto s_end = bla.end();
    for( auto t=s_beg; t!=s_end;++t) {
        std::cout << ( *t )->m_strName << std::endl;
    }
}

【问题讨论】:

  • 在哪一行报错?

标签: c++ c++11 stdmap


【解决方案1】:

问题在于get_value 引用了pair&lt;K,V&gt;,但传递的是对映射值类型pair&lt;const K,V&gt; 的引用。这需要进行转换,这需要将键和值都复制到新的对中。您收到错误是因为无法复制 unique_ptr。

解决方案 1:更改 get_value 以接受对 pair&lt;const K,V&gt; 的引用以匹配 TMap::value_type。这允许函数直接接受对映射值的引用。

解决方案 2:将 get_value 实例化为 const int 而不是 int;这将与解决方案 1 具有相同的效果。

解决方案 3:将 get_value 实例化为 const unique_ptr &amp; 而不是 unique_ptr,以便它采用包含对映射值的引用的对。无需复制 unique_ptr 即可创建此临时对。

【讨论】:

  • 解决方案 1 有效(我没有检查其他问题)!谢谢你拯救了我的一天。
猜你喜欢
  • 2021-04-15
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
  • 2023-03-31
  • 2012-02-03
  • 2018-11-15
  • 1970-01-01
相关资源
最近更新 更多