r/ProgrammerHumor • • Jan 28 '23

Meme C++

Post image
53.9k Upvotes

1.5k comments sorted by

View all comments

Show parent comments

3

u/Tranzistors Jan 28 '23

There are good guidelines.

pointer vs reference vs rvalue reference vs smart pointer

  • reference when the target totally exists, recommended;

  • raw pointer when the target may or may not exist;

  • I.11 smart pointer when you own the resource and it lives on the heap;

  • local variable when you own it and it lives on the stack;

  • rvalue when the data doesn't need to live longer than the statement.

#define vs constexpr

ES.31 whenever possible use constexpr

throw exception vs return error code vs set errno

First of all, figure out if you are in an environment where you are allowed to throw. But if you can.

  • I.10 usually throw (e.g. failed to construct a std::vector);

  • if it's 'normal' that the operation could not deliver desirable outcome, return std::expected (e.g. smallest_prime_between(int min, int max);

  • errno is sad (E.28), only use in legacy, preferably wrap.

explicit cast vs implicit cast

explicit where reasonably possible; implicit is where dragons live.

lock_guard vs scoped_lock

CP.21

#ifndef vs #pragma once

SF.8 #ifndef, #pragma is non-standard. Or use modules (whenever they become available).

.cc vs .cpp file extension, .h vs .hpp file extension

NL.27; .cpp + .h

CRTP vs inheritance

C.hier. Cool guys prefer static inheritance, but I dunno.

1

u/throw3142 Jan 28 '23

Thanks for the reference. I agree on all counts - the problem is that not everyone does :) Since the population of C++ devs is so varied, you have a lot of ppl who still prefer the old C-like style and a lot of newbies who just pick a random style when they don't know what to do. Often within the same codebase.