Hacker News new | ask | show | jobs
by rosshemsley 3004 days ago
I actually thought this would be about yak shaving due to the huge number of ways to achieve everything in modern C++xy.

My internal monologues when writing modern C++ look a lot like this...

So I have to return from this function... it uses a lot of resources, so I don't want to copy it. But then there is RVO... Although is this actually NRVO? What was that rule again? I guess I can rely on move semantics? But only Scott Meyers himself understands those and he promptly exited the C++ community after figuring them out... And anyway, what if I want to change the ownership explicitly? Let's just use a unique_ptr. Oh but actually I mostly want to share it when I have returned, and that means two blocks of memory will be allocated per pointer instead of the optimal "single" allocation with the reference count at the beginning. Although maybe that's only in libc++? oh, and what if there is an error, should it return nullptr in that case?..

4 comments

I realize that you're mostly ranting, but on the off chance that you're serious: check out std::make_shared. It's a helper function that can allocate storage for the object and shared_ptr's control block in one go. It comes with its own caveats (what doesn't in C++?), but it has the answer to your concern about allocations.
To add: according to cppreference, all known STL implementations leverage this optimization. This used to be specific to Microsoft's STL implementation, but apparently all the major STL vendors are now on-board with it.
make_shared traces its roots back into the original boost implementation.
Yep I know it :)

My joke was "Oh, I should return a unique_ptr<>, but then I will be losing out on the make_shared optimization" ;)

C++ move semantics are complicated, definitely, but Meyers actually somewhat complicated them more in the way he describes "universal references". I don't quite think that was his intention. It's not that only Meyers understands them: it's that he understands them in a way that only a language lawyer needs to.

Like your hypothetical train of thought, it just goes to show that you can complicate C++ usage a lot more than necessary. Despite all the fancy new stuff for dealing with pointers and move semantics (and lvalues, rvalues, so-called universal references, etc.), the old standby of raw pointers still do the job just as well as they always have. You can always make some kind of note to come back to something later and decide whether it makes sense to use some other kind of pointer.

> Scott Meyers ... promptly exited the C++ community

Huh, TIL http://scottmeyers.blogspot.fr/2015/12/good-to-go.html

I remember reading blog post and wondering what was going on. That was more than two years ago. Does anyone know what he has been up to since?

EDIT: He was invited as a keynote speaker for DConf 2017: https://youtu.be/RT46MpK39rQ?list=PL3jwVPmk_PRxo23yyoc0Ip_cP...

C++17 has guaranteed RVO.