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;

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I agree with the rationale. But interestingly, using std::unordered_map with unique_ptr has no any problem.
@SuperBald, interesting. I found that following your hint: stackoverflow.com/questions/3906295/c-unique-ptr-and-map, it seems like the answer we are looking for.
Thanks a lot! That is really the most relevant post!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.