Skip to content

Unsafe Constant Initialization #269

@mahiuchun

Description

@mahiuchun

In ignition::math::Color the color constants are defined like public: static const Color Cyan;. While the resulting interface is nice to use, it could cause static initialization order fiasco as C++ makes no guarantee that global variables in this form is going to be initialized in usage order. In other words, another global variable could use Color::Cyan and be initialized first.

A simple fix is to convert to a function form like the following:
public: const Color& Cyan() { static auto *c = new Color(0, 1, 1, 1); return *c; }

Another solution is more involved but it could retain the ability to refer to constants without parentheses.

  1. Add a constexpr constructor to the class.
  2. In another class, say, ColorConstants, use public: static constexpr Color Cyan = {0, 1, 1, 1};

Both solutions represent a API/ABI change, so I would like to hear some feedback first before sending out PRs.

The Vector classes might be affected by this too.

Metadata

Metadata

Labels

Breaking changeBreaks API, ABI or behavior. Must target unstable version.bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions