C++ Logo

std-proposals

Advanced search

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

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Thu, 1 Sep 2022 14:22:04 +0100
You can use pointer-interconvertibility with union members and with first
data members.
http://eel.is/c++draft/basic.compound#def:pointer-interconvertible

Of course, you lose constexpr, and because you're using reinterpret_cast
it's ugly and difficult to tell whether you've accidentally written
something with undefined behavior.

On Thu, 1 Sep 2022, 13:51 Lewis Baker via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> 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
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2022-09-01 13:22:19