[ub] Implementation of assignment in std::optional and Core issue 1404: Object reallocation in unions

Nikolay Ivchenkov mk.ivchenkov at gmail.com
Thu May 30 15:57:47 CEST 2013


On Thu, May 30, 2013 at 4:45 PM, Ville Voutilainen <
ville.voutilainen at gmail.com> wrote:

>
> If you just do an opt.emplace(n2); followed by opt->ref = 1; you never
> formed a pointer/reference to the original
> object
>

Why? I presume that the intention behind 3.8/7 was to allow optimizations
described below:

    #include <iostream>

    struct X
    {
        int &ref;
    };

    void f(X &);

    int main()
    {
        int n = 0;
        X x{n};
        f(x);
        x.ref = 5;
        std::cout << n << std::endl;
    }

Here a compiler is allowed to assume that

    x.ref = 5

is equivalent to

    n = 5;

and therefore

    std::cout << n << std::endl;

is equivalent to

    std::cout << 5 << std::endl;

regardless of the definition of f (which may be unknown for compiler).
There is no legal way to modify reference x.ref after its initialization so
that it would refer to a different location. Even if we overwrite the
storage of x by construction of a new object of type X at address &x (our f
could do such thing), a compiler may assume that x.ref is untouched. The
same applies to the original example with optional.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.open-std.org/pipermail/ub/attachments/20130530/511abd3c/attachment.html 


More information about the ub mailing list