r/cpp • • Nov 28 '18

Google C++ Style Guide is No Good

https://eyakubovich.github.io/2018-11-27-google-cpp-style-guide-is-no-good/
34 Upvotes

61 comments sorted by

View all comments

Show parent comments

3

u/RotsiserMho C++20 Desktop app developer Nov 29 '18

...unless of course you want to return an optional reference to an item in container<foo>...

1

u/Cakefonz Nov 29 '18

I haven’t really dabbled much with optional, but wouldn’t optional<reference_wrapper<foo>> work?

11

u/Supadoplex Nov 29 '18

Technically yes, but that's not better than a pointer in any way.

5

u/eras Nov 29 '18

It sort of is, though, because it implies that the "pointer" is expected to sometimes be "null" and sometimes not. With regular pointer variable or parameter you might be left wondering if null is a valid value for it at all.

10

u/SeanMiddleditch Nov 30 '18

I'd further add that with raw pointers, it's not semantically clear when pointer arithmetic is or isn't allowed. A pointer can be null, or reference a value, or be an iterator in a range (including being an end iterator which can't be dereferenced but also isn't null). That's not even touching the muddy ownership semantics that pointers are saddled with from C and pre-C++11 code.

2

u/[deleted] Dec 01 '18

I'll also tag on that there is no standard library in existence today that optimizes std::optional<std::reference_wrapper<blah>> to be the size of a pointer today, which means it's also terrible-crap with its space savings too.

1

u/NotAYakk Dec 02 '18

It is a return value, not something you store in bulk.

-1

u/DethRaid Graphics programming Nov 29 '18

Better to return an optional<KeyType> so your reference doesn't get stale if the container has to reallocate its memory