1

I am trying to compile google's sparse hash map, but there is an error. The error message seems to be related to using unique_ptr. After I removed unique_ptr compiling succeeded.

  google::sparse_hash_map<std::string, std::unique_ptr<int>> testers_;

The error message is as below. Any suggestions? Thanks a lot!

build/libgcc/include/c++/trunk/bits/stl_pair.h:127:17: note: explicitly defaulted function was implicitly deleted here
  constexpr pair(const pair&) = default;
            ^

build/libgcc/include/c++/trunk/bits/stl_pair.h:102:11: note: copy constructor of 'pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char>, std::basic_string<char> >, std::unique_ptr<int, std::default_delete<int> > >' is implicitly deleted because field 'second' has a deleted copy constructor
  _T2 second;                /// @c second is a copy of the second object
      ^

/build/libgcc/include/c++/trunk/bits/unique_ptr.h:356:7: note: 'unique_ptr' has been explicitly marked deleted here
  unique_ptr(const unique_ptr&) = delete;
sokkyoku
  • 2,161
  • 1
  • 20
  • 22
SuperBald
  • 109
  • 1
  • 12

1 Answers1

1

I think there is a problem at the root.

unique_ptr has the intent of having only one owner of the pointer to a specific resource. The last one that retrieve a copy of the unique_ptr.

Thinking about a container, it means that the map cannot hold a copy of the object you are pointing to if someone is asking for the resource, invalidating the map itself (ie: the entry will have an invalid unique pointer inside after the first "get" of it)

I believe that some of the Cx11 constraints are forbidding the compilation avoiding the mistake.

Stefano Buora
  • 1,052
  • 6
  • 12
  • 1
    I agree with the rationale. But interestingly, using std::unordered_map with unique_ptr has no any problem. – SuperBald Feb 07 '17 at 16:09
  • 1
    @SuperBald, interesting. I found that following your hint: http://stackoverflow.com/questions/3906295/c-unique-ptr-and-map, it seems like the answer we are looking for. – Stefano Buora Feb 07 '17 at 16:37
  • Thanks a lot! That is really the most relevant post! – SuperBald Feb 07 '17 at 17:02