C++ Logo

sg20

Advanced search

Re: Introducing references

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Wed, 26 Jan 2022 14:33:04 -0500
On Wed, Jan 26, 2022 at 1:03 PM Victor Eijkhout via SG20 <
sg20_at_[hidden]> wrote:

> On , 2022Jan26, at 11:02, JC van Winkel <jcvw_at_[hidden]> wrote:
>
> Hi,
>
> Note that http://wg21.link/p1389 was written to give advice about what
> patterns to use and what to avoid.
>
>
> Understood. And I was saying that the suggested patterns is
> unimplementable.
>

FWIW, I teach
- pass-by-value
- problems: performance of all those copies; how to write an out-parameter?
- C solution: pointers (a pointer holds a memory address)
- pass-by-pointer
- C++ enhancement: references (***)
- pass-by-reference
- problem: accidental modification of the caller's thing
- solution: `const`
- pass-by-const-reference
- guideline: pass large objects by const&, small cheap ones by value
- guideline: pass out-parameters by pointer

This happens over the course of about 10–20 slides. Right at the (***)
mark, I do have sample code of the form
    int& r = i;
    r = 2; // modifies i
of the form disparaged by P1389. However, it's also surrounded by the
*larger* context where we're talking about function parameters, exactly as
prescribed by P1389. Also, that slide is presented in that form
specifically because we want to compare references' syntax against
pointers' syntax from 2–3 slides earlier:
    int *p = &i;
    *p = 2; // modifies i
I sympathize with Victor's point that teaching references does require
*one* slide
that presents references outside of parameter lists. But generally I agree
with P1389's guidance that you really *don't* want to emphasize the use of
references outside of function parameter lists (and, eventually, getter
return types). The trick is to get past that *one* slide really quickly and
emphasize the parameter-list usage. Don't spend multiple slides on local
variables of reference type; don't do exercises where you bind references
to other references and stuff like that; just say what they are and then
get on with using them as they're intended to be used. Easy peasy.

–Arthur

Received on 2022-01-26 19:33:16