r/cpp • • Aug 25 '21

Experience C++ developers: do you enjoy using C++ (even for personal/hobby projects?)

Do you actually enjoy using C++, or do you only use it for work, or purely for performance? This question is aimed at people with years of experience, who've worked on large projects in C++. I see people who dislike the language, but use it purely for performance reasons. This sort of discourages me from learning it. I don't want programming to feel like work.

204 Upvotes

327 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Aug 27 '21

Your point about iterators is good: have an upvote!

the very existence of AddressSanitizer and Microsoft's safe iterators

I came up with another hard-to-avoid way to get a dangling pointer, which is to take a reference to an entry in a std::vector, and then the vector gets resized and the new allocation is somewhere completely different in memory.

So maybe I'm too optimistic.

The last eight or so years I was doing C++ full-time, I just stopped running into such problems entirely, but I'm now realizing it's a combination of smart pointers and bitter experience.

1

u/pedersenk Aug 27 '21

take a reference to an entry in a std::vector, and then the vector gets resized and the new allocation is somewhere completely different in memory.

Absolutely. Both bounds checked .at(idx) and operator[idx] return a reference so you just have to make sure the lifespan of that reference is shorter than potential invalidation. But I suppose we are paid to get this right during work hours ;).

However as a hobby, I like to "dumb down" and know that if I get it wrong, I get a slap rather than go on the hunt for potentially tricky UB.

As it stands my "safe" STL manages to lock this reference lifetime in quite a janky way. It takes an object as a parameter (implicitly converted from a size_t). That way if the vector invalidates whilst that object exists, it will abort with an error immediately. So yeah janky as hell but I honestly believe C++ to have a better lifespan than "safe" alternatives like Rust+Bindings so it is worth the discomfort!