C++ Logo

sg12

Advanced search

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

From: Nikolay Ivchenkov <mk.ivchenkov_at_[hidden]>
Date: Thu, 30 May 2013 17:57:47 +0400
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.

Received on 2013-05-30 15:57:48