Skip to content

Commit

Permalink
events: Remove strict-aliasing warning
Browse files Browse the repository at this point in the history
Several opaque buffers are used to to wrap c++ classes to pass
to the c layer. The reinterpret cast to c++ classes is fine as long
as the underlying buffer is not interpreted as different incompatible
types, or else the behaviour is undefined.

In the equeue_tick_init function, placement new is used to initialize
the buffers. However, this interprets the buffer as a simple array
of bytes, not the actual class type. Later the buffer is casted to
the class type. From the point of view of the compiler, these two
types are incompatible, and the compiler is free to reorder the
operations under the assumption that they can't affect each other.

Reinterpet casting the buffer to a class pointer before using
placement new insures that the buffer is only interpreted as a single
type. Or simple using the return value from placement new will handle
the aliasing appropriately.
  • Loading branch information
geky committed Aug 4, 2019
1 parent b2a4d7a commit d07c9a5
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions equeue_mbed.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,12 @@ static void equeue_tick_init() {
"The equeue_timer buffer must fit the class Timer");
MBED_STATIC_ASSERT(sizeof(equeue_ticker) >= sizeof(Ticker),
"The equeue_ticker buffer must fit the class Ticker");
new (equeue_timer) Timer;
new (equeue_ticker) Ticker;
Timer *timer = new (equeue_timer) Timer;
Ticker *ticker = new (equeue_ticker) Ticker;

equeue_minutes = 0;
reinterpret_cast<Timer*>(equeue_timer)->start();
reinterpret_cast<Ticker*>(equeue_ticker)
->attach_us(equeue_tick_update, 1000 << 16);
timer->start();
ticker->attach_us(equeue_tick_update, 1000 << 16);

equeue_tick_inited = true;
}
Expand Down

0 comments on commit d07c9a5

Please sign in to comment.