C++ Logo


Advanced search

Re: [std-proposals] Use optional<T> as though it were T

From: Thiago Macieira <thiago_at_[hidden]>
Date: Sun, 25 Jun 2023 10:21:58 -0700
On Sunday, 25 June 2023 04:53:06 PDT Frederick Virchanza Gotham via Std-
Proposals wrote:
> Now let's say that over 15 years, your program gets a lot bigger and
> so now you want to start conserving RAM. This global object has a
> constructor that allocates 100 megabytes of RAM, and so you decide to
> delay its construction until it's actually needed, so you change it
> to:
> optional<T> g_obj;

I think the idea has some merit, but the implementation you're suggesting is
overcomplicated, overengineered and has no chance of ever getting accepted.
You should start by forgetting std::optional and look at a separate

What you *really* need is what std::optional has internally, which is:

  alignas(T) unsigned char g_obj_storage[sizeof(T)];
  auto &g_obj = *reinterpret_cast<T *>(g_objj_storage);

And you simply have to arrange to initialise that object before ever using the
g_obj global.

Strictly speaking, the code above alone is UB because forming that reference
is already UB. You can solve it, like any problem in computing, with an extra
level of indirection. If you must keep source compatibility, you could define a
macro so you only perform that expression after you're sure the object has
been created. Or you can move it into a function, but then you have to suffer
adding () to the source.

I would call the price of refactoring the code base to add () or -> more than
acceptable, so I doubt you'll get a feature past the committee that attempts
to work around that.

Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-06-25 17:22:00