C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Proposal: std::obj_from_dmbr

From: Lewis Baker <lewissbaker_at_[hidden]>
Date: Thu, 1 Sep 2022 22:20:58 +0930
On Thu, Sep 1, 2022 at 4:06 PM Lénárd Szolnoki via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> ... keep in mind that you can already do this if your subobject is a base
> member instead of a non-static data member of the complete object. I don't
> know if this would be applicable for your use case though, this proposal
> does add some flexibility that is not there with base members.
>
>
Unfortunately, I cannot always guarantee that I can use the base-class
trick to achieve this.

In some cases I want to be able to defer construction of the child object
until later.
e.g. by using a manual_lifetime<T> wrapper that contains storage for an
object of type T and that lets me manually call the constructor/destructor
at the appropriate points.

template<typename T>
struct manual_lifetime {
  template<typename... Args>
  void construct(Args&&... args);
  void destroy();
  T& get();

  alignas(T) std::byte storage[sizeof(T)];
};

struct Parent {
  int some_data;
  manual_lifetime<Child> child;
};

Trying to go from the 'Child' constructed in-place in the storage of the
manual_lifetime<Child> member would require something like:

Child& child = ...;
Parent& p = containing_object_of_member(
  &Parent::child,
  containing_object_of_member(
    &manual_lifetime<Child>::storage,
    reinterpret_cast<std::byte(&)[sizeof(T)]>(child)));

Another use-case is that the sub-objects might be union-members.
e.g.

struct Parent {
  int some_data;
  union {
    Child1 child1;
    Child2 child2;
  };
};

And where I want to be able to go from address of child1 member to address
of Parent.

I don't think you can do this deferred construction with base-classes.

- Lewis

Received on 2022-09-01 12:51:10