std :: map中的C ++ 11类作为具有私有构造函数的值

时间:2016-07-27 05:42:43

标签: c++11 private stdmap

这是该类的简化版本,它作为值存储在地图中,在VS2008中正常工作(请注意所有成员都是私有的):

class Value{
    friend class FriendClass;
    friend class std::map<std::string, Value>;
    friend struct std::pair<const std::string, Value>;
    friend struct std::pair<std::string, Value>;

    Value() {..}
    Value(Value const& other) {..}

    ... rest members...
};

代码(从FriendClass调用,因此可以访问私有构造函数):

FriendClass::func()
{
    std::map<const std::string, Value> map;
    map.insert(std::make_pair(std::string("x"), Value()));
}

这不编译VS2008中的任何错误,但在VS2015 / C ++ 11上失败:

file.cpp(178): error C2664: 'std::_Tree_iterator>>> std::_Tree>::insert(std::_Tree_const_iterator>>>,const std::pair &)': cannot convert argument 1 from 'std::pair' to 'std::pair &&'
      with
      [
          _Kty=std::string,
          _Ty=Value,
          _Pr=std::less,
          _Alloc=std::allocator>
      ]
      and
      [
          _Kty=std::string,
          _Ty=Value
      ]
  file.cpp(178): note: Reason: cannot convert from 'std::pair' to 'std::pair'
      with
      [
          _Kty=std::string,
          _Ty=Value
      ]
  file.cpp(178): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

如果我将Value复制构造函数设为public,它在VS2015中编译也很好。

但那是私有目的,只能用于std :: map和std :: pair。但是,似乎在C ++ 11中另外的朋友访问也需要声明。这些是什么?

谢谢。

1 个答案:

答案 0 :(得分:0)

我无法访问您提到的编译器,但这是我在g ++ 5.3上看到的内容。

考虑以下基本相同版本的问题:

#include <map>                                                                                                                             
#include <utility>


class foo
{
    friend std::pair<const int, foo>;

    foo(const foo &other){}

public:
    foo(){}
};


int main()
{
    using map_t = std::map<int, foo>;

    map_t m;
    m.insert(std::make_pair(2, foo()));
    // m.emplace(2, foo());
}

(默认的ctor是public,但这不是必需的,只是缩短了示例。)

main中,请注意两行

m.insert(std::make_pair(2, foo()));
// m.emplace(2, foo());

撤消评论构建正常,但显示的版本不是:

/usr/include/c++/5/bits/stl_pair.h: In instantiation of ‘constexpr    std::pair<_T1, _T2>::pair(_U1&&, const _T2&) [with _U1 = int; <template-parameter-2-2> = void; _T1 = int; _T2 = foo]’:
/usr/include/c++/5/bits/stl_pair.h:281:72:   required from ‘constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename   std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&) [with _T1 = int; _T2 = foo; typename std::__decay_and_strip<_T2>::__type = foo; typename std::__decay_and_strip<_Tp>::__type = int]’
stuff.cpp:21:34:   required from here
stuff.cpp:9:2: error: ‘foo::foo(const foo&)’ is private
 foo(const foo &other){}
 ^

查看源代码std_pair.h表明它确实在尝试调用复制构造函数。不幸的是,您friend编辑std::pair,而不是std::make_pair

emplace版本没有此问题,但我怀疑这是依赖于实现的。通常,如果您希望容器存储完全不透明的类,我建议您使用std::shared_ptr的容器。这允许您完全指定哪个函数/类可以在您自己的代码中创建/复制对象,并且不对库的代码进行任何假设。

相关问题