C++ Logo

sg20

Advanced search

Re: [SG20] A draft paper to fix the range-based for loop to make it teachable

From: Amir Kirsh <kirshamir_at_[hidden]>
Date: Fri, 13 Nov 2020 11:04:24 +0200
> FWIW, this is the approach other library functionality should consider to
reduce the risk of dangling.
> either delete the temporary case, or think hard about a non-dangling
return type, e.g., by value, if at all.
> may be we can find a solution to enable such a situation where it is
obvious the programmer guarantees the lifetime of the temporary,
> but I am waiting for an insight, how to approach it.

Taking this approach in users' code is possible, though a bit cumbersome
today:

class Person {
    std::string name;
public:
    Person(std::string name): name(std::move(name)) {}
    const std::string& getName() const & { return name; }
    const std::string& getName() const && = delete;
    // or:
    // std::string getName() const && { return name; }
};

Maybe P0847 - Deducing this might be a solution for a more elegant and less
cumbersome way? I'm not sure.



On Fri, Nov 13, 2020 at 10:06 AM Peter C++ via SG20 <sg20_at_[hidden]>
wrote:

> see below
>
> Sent from Peter Sommerlad's iPad
> +41 79 432 23 32
>
> > On 13 Nov 2020, at 08:49, Nicolai Josuttis via SG20 <
> sg20_at_[hidden]> wrote:
> >
> >> One more technical note. Do you think that with your change proposed,
> >> one could also think of dropping the deleted rvalue reference overload
> >> of std::as_const? (And possibly similar other functions.) As far as I
> >> understand, with your proposed changes, something like
> >>
> >>> for (auto & elem : std::as_const(getVector())) { ~~~ }
> >>
> >> would now work. Is it worth including it?
> >>
> > THAT is an interesting example, thanks.
> > In principle, you are right, but exactly to avoid problems like the one
> > above as_const() is deleted for temporary objects:
> >
> >> template <class T> void as_const(const T&&) = delete;
> >
> > So, while this could work now, it still would not compile.
>
> FWIW, this is the approach other library functionality should consider to
> reduce the risk of dangling. either delete the temporary case, or think
> hard about a non-dangling return type, e.g., by value, if at all. may be we
> can find a solution to enable such a situation where it is obvious the
> programmer guarantees the lifetime of the temporary, but I am waiting for
> an insight, how to approach it.
>
> regards
> peter
> --
> SG20 mailing list
> SG20_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/sg20
>

Received on 2020-11-13 03:04:42