C++ Logo

sg20

Advanced search

Re: Introducing references

From: Nico Josuttis <nico_at_[hidden]>
Date: Wed, 26 Jan 2022 21:36:47 +0100
Two comments :

- To understand references most students learn them best when thinking about references as "temporary additional name".

- As with universal references become state of the art for ordinary programmers with C++20, I wonder whether we should now teach them early or even first.


Am 26. Januar 2022 20:33:04 MEZ schrieb Arthur O'Dwyer via SG20 <sg20_at_[hidden]>:
>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

-- 
Nico Josuttis
(sent from my mobile phone) 

Received on 2022-01-26 20:36:53