C++ Logo

SG12

Advanced search

Subject: Re: [ub] Implementation of assignment in std::optional and Core issue 1404: Object reallocation in unions
From: Nikolay Ivchenkov (mk.ivchenkov_at_[hidden])
Date: 2013-05-30 08:57:47


On Thu, May 30, 2013 at 4:45 PM, Ville Voutilainen <
ville.voutilainen_at_[hidden]> 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.



SG12 list run by herb.sutter at gmail.com