Using (void *) as an identifier type

In my program, I have objects (of the same class) that must have a unique identifier. For simplicity and performance, I decided to use the address of the object as an 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; }
}

It seems to work fine, but gcc gives me a warning with strict anti-aliasing. I understand that the code would be bad if the identifier was used to transmit data. Fortunately, this is not the case, but the question remains: will aliases be optimized? And how to avoid the warning?

Note. I do not want to use (char*), as this implies that the user can use the data to copy, which he cannot!

+3
source share
5 answers

You are breaking a logical constant that returns an object as mutable in the const method.
As Neil points out, no cast is required.

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

You can try using a type uintptr_tinstead void*. uintptr_t- an integer type that is defined as large enough to hold any pointer value. And since this is not really a pointer, the compiler will not point to any problems with the alias.

class MyClass {
public:
    typedef uintptr_t identity_t;
    identity_t id() const { return (identity_t)this; }
}
+4

return static_cast<void*>(this);

, void * .

dynamic_cast(this);, , , , , RTTI- .

, const, .

+2

. , ( id ), . , const void* .

, , size_t. , -.

+1

MyClass *?

intptr_t?

0

Source: https://habr.com/ru/post/1725028/


All Articles