C++ Logo

sg20

Advanced search

Re: Introducing references

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Wed, 26 Jan 2022 23:43:57 -0500
On Wed, Jan 26, 2022 at 10:40 PM Yongwei Wu <wuyongwei_at_[hidden]> wrote:

> On Thu, 27 Jan 2022 at 04:03, Victor Eijkhout via SG20 <
> sg20_at_[hidden]> wrote:
>
>>
>> Why do you teach the “pass by pointer”?
>>
>
> My 2 cents here (in addition to Arthur’s good reply). I think there is a
> use in daily programming to describe ‘potentially null’. Some people prefer
> std::optional, but it has a bad performance impact, especially on large
> objects, and it can only be used on an ‘in’ parameter, but not an ‘out’ or
> ‘in-out’ parameter. If there is no ownership involved and the argument can
> be ‘missing’, I would recommend using a pointer (as versus a reference that
> is not allowed to be null).
>

It's certainly important to teach that pointers *can be null* (and that C++
has a keyword for this — `nullptr`!), but I don't think that's relevant to
out-parameters or "pass by pointer" per se. When we're passing by pointer,
we're always passing *some thing* by pointer:
    f(x, &y); // x is passed by value or const&, we don't care which; y is
passed by pointer, indicating an out-parameter
In my particular motivating example, where we're just trying to invent a
way to pass a std::string efficiently without copying, there's obviously no
reason to ever pass a null pointer there; the pointer we pass points to *the
string*, by definition. Likewise for an out-parameter, the pointer we pass
points to *the place the result is going to go*, by definition. Sure,
hypothetically someone might call
    int x;
    f(x, nullptr);
passing garbage for the first parameter and null for the second; but that's
obviously foolish and we don't need to go there.
(If a student brings it up, there's lots of philosophically interesting
stuff around invariants that aren't actually invariant, especially now that
we have C++20 Concepts. For example, C++20 defines
`std::totally_ordered<float> == true`, despite the existence of `NaN`; with
basically the same rationale I gave above: "[comparing things against NaN]
is obviously foolish and we don't need to go there." C++ is full of corner
cases where something is *physically* possible but *semantically* a bad
idea. variant::valueless_by_exception() also comes to mind (but I would
rather tell a student about NaN than tell them about
valueless_by_exception! :D)

–Arthur

>

Received on 2022-01-27 04:44:09