Search code examples
c++identitystrict-aliasing

Using (void*) as a type of an identifier


In my program, I have objects (of the same class) that must all have a unique identifier. For simplicity and performance, I chose to use the address of the object as identifier. And to keep the types simple, I use (void*) as a type for this identifier. In the end I have code like this:

class MyClass {
public:
  typedef void* identity_t;
  identity_t id() const { return (void*)this; }
}

This seems to be working fine, but gcc gives me a strict-aliasing warning. I understand the code would be bad if the id was used for data transfer. Luckily it is not, but the question remains: will aliasing optimisations have an impact on the code produced? And how to avoid the warning?

Note: I am reluctant to use (char*) as this would imply the user can use the data for copy, which it can not!


Solution

  • You are violating logical constness returning the object as mutable in a const method.
    As Neil points out, no cast is needed.

    class MyClass {
    public:
      typedef const void* identity_t;
      identity_t id() const { return this; }
    };