By Ammar Husain

2014-08-04 18:10:28 8 Comments

I posted a similar quetion regarding using pointers as Keys on maps in C++ STL. How are pointers hashed in unordered_maps when used as Keys. More specifically if I define:

std::unordered_map< CustomClass*, int > foo;

Would the default C++ std::hash implementation work to handle these pointers? Is it safe to use? Is this good practice?


@Mark Ransom 2014-08-04 18:16:43

std::hash<T*> is defined but the details of how it operates are implementation dependent. It will certainly be safe to use, and I'd consider it good practice - as long as it's the pointer you need as the key, and not the object contents itself.

@echo 2018-11-06 14:53:17

Why does the pointer need to be a pointer to the key instead of a pointer to the entire object? What if I want the key to be a pointer to the object itself?

@Mark Ransom 2018-11-06 15:24:52

@echo I think you missed my point - the pointer itself is the key, not a pointer to the key. So two objects will be separate in unordered_map even if the contents of the key object are identical.

@echo 2018-11-06 15:37:16

Ahhh ok, yes I misunderstood your original comment but now re-reading with new context, I understand what you were saying. It seems like in cases where object contents can be identical for two distinct objects, and the objects don't have a unique key/identifier, you might want to hash object pointers.

@Mark Ransom 2018-11-06 16:25:54

@echo I've actually used this in real code. If you have a callback that passes a void pointer, and you want to know if the object still exists before you use the pointer, you can look it up in an unordered_set.

Related Questions

Sponsored Content

39 Answered Questions

22 Answered Questions

[SOLVED] What is the "-->" operator in C++?

1 Answered Questions

[SOLVED] The Definitive C++ Book Guide and List

  • 2008-12-23 05:23:56
  • grepsedawk
  • 2314678 View
  • 4245 Score
  • 1 Answer
  • Tags:   c++ c++-faq

13 Answered Questions

[SOLVED] What is a smart pointer and when should I use one?

14 Answered Questions

[SOLVED] Secure hash and salt for PHP passwords

21 Answered Questions

[SOLVED] Why should I use a pointer rather than the object itself?

  • 2014-03-03 11:54:16
  • gEdringer
  • 307156 View
  • 1567 Score
  • 21 Answer
  • Tags:   c++ pointers c++11

33 Answered Questions

[SOLVED] How can I generate an MD5 hash?

1 Answered Questions

[SOLVED] How std::unordered_map is implemented

2 Answered Questions

[SOLVED] C++ unordered_map using a custom class type as the key

5 Answered Questions

[SOLVED] Pointers as keys in map C++ STL

  • 2014-08-04 16:06:16
  • Ammar Husain
  • 25300 View
  • 38 Score
  • 5 Answer
  • Tags:   c++ pointers map stl

Sponsored Content