Remix.run Logo
▲ tolugenius 7 hours ago

C++ is a language I heard is very "beginner unfriendly, and expert friendly" and it's true, I'm trying to relearn and really not clicking with me, anyone have tips on relearning or better sites than even learncpp?

▲gaflo 42 minutes ago | parent | next [-]

I wouldn't say it's expert friendly either. It is very powerful, but it's definitely not as ergonomic to use as more modern languages. Before agents/LLMs you would probably have cppreference.com open every time you are implementing something to check whether the STL is designed as you think. Compilation errors are as explicit as it gets (and thus a bit verbose), but they would help an expert to very quickly understand what was going wrong in a program.

I think part of the problem is that there are usually 3 different ways to achieve the same semantics, but there would be some subtle technical differences. From my perspective a lot of the problems with C++ come from the incoherent vision for what the language was supposed to be and especially the insistence on backwards compatibility caused significant bloat (design/technical debt) over time.

▲William_BB 7 hours ago | parent | prev | next [-]

Classic C++ books and cppcon are probably the best ways to learn the language if you don't have exposure to a modern C++ codebase (at least C++17).

▲pjmlp 7 hours ago | parent [-]

Tour of C++, last edition, would be a good one.

▲coldpie 7 hours ago | parent | prev | next [-]

Learn (like, really learn) C first. C is a reasonably easy language to learn, with only a few weird corners mostly due to its relevance to very old computing concepts. Build a few toy programs, maybe a video game or two, play around with memory allocations and struct aliasing and file I/O and function pointers.

C++ is (wave hands vigorously) roughly built on top of C's core concepts, so if you know C really well you can (continue waving hands) actually map most of C++'s basic concepts on top of how C works. For example in object methods, the 'this' pointer is actually just silently passed as the first parameter to a function. Class vtables are (at a very abstracted level) just arrays of function pointers. Letting you map those concepts down to a simpler representation like C means C++'s magic starts to lose its magic. Understanding how the class hierarchy is mapped to C can tell you why the 'virtual' keyword exists, and why you need proper copy constructors for those objects but not ones without vtables; and it gives clues for what pure virtual functions are, and why you can't allocate an object with one.

So yeah. Start with C, then figure out the bizarre, incredibly complex maze of abstractions that C++ stacked on top of it.

▲pjmlp 7 hours ago | parent [-]

This will only bring bad practices in modern C++, the root of all C/C++ discussions in security reports.

▲coldpie 6 hours ago | parent | next [-]

Curious if you can elaborate. I found learning C to be a really good stepping stone to understanding many of C++'s design choices (eg stuff like why the 'virtual' keyword exists & works as it does; or why a class's private members must be declared in the public header). It also gets you more familiar with non-interpreted language concepts like the compiler and the linker before C++ turns those into multi-headed beasts.

▲0x457 2 hours ago | parent | next [-]

I'd distinguish between understanding why C++ was designed the way it was and learning how to write idiomatic C++. C is certainly useful for the former, but many practices considered perfectly normal in C are considered (very) bad practice in C++.

This is also why I dislike the term "C/C++" when referring to them as if they were a single language. They are two distinct languages with substantially different idioms.

What I hate about C++ is that it offers a myriad of ways to accomplish the same thing, ranging from outright terrible to genuinely good. Learning C first can reinforce habits that you'll later have to unlearn.

▲pjmlp 6 hours ago | parent | prev [-]

C raw arrays and strings should only be used for "unsafe" C++ code, in the implementation of safer types, with bounded checked interfaces, or in interop code with C libraries, properly wrapped in safe accessors for example.

Use of references for any non nullable pointer.

RAII for heap allocated types, eventually new/delete, leave malloc()/free() family with sizeof type math for interop with existing C code.

Prefer standard library algorithms with proper bounds checking, instead of memsomething and strsomething function family.

Preprocessor magic, when templates and constexpr are type safe, and can even be single stepped on a modern IDE.

Just some examples out of my mind.

▲PhilipRoman 4 hours ago | parent [-]

I wholeheartedly disagree with the idea that all C++'s problems come from backwards compatibility with C. Even "pure" C++ alone without C constructs brings enough footguns.

  struct Config {
    std::vector<std::string> names;
    const std::vector<std::string>& getNames() const { return names; }
  };
  Config loadConfig();
  
  // which of these are safe?
  for (const auto& n : loadConfig().names)      { use(n); }  // A
  for (const auto& n : loadConfig().getNames()) { use(n); }  // B
  
  const auto& v1 = loadConfig().names;          // C
  for (const auto& n : v1) { use(n); }
  
  const auto& v2 = loadConfig().getNames();     // D
  for (const auto& n : v2) { use(n); }
Trick question btw
▲plorkyeran 3 hours ago | parent | next [-]

C in C++20, A, B and C in C++23. This does sort of fall under a backwards compatibility issue, albeit not with C, as making D valid was considered too much of a breaking change.

▲PhilipRoman an hour ago | parent [-]

I'm no C++ expert, but in P2012R0 it even gives this specific example, indicating that A is OK in c++20:

[..] One recent real-world example by one of the authors is the following: Improving the following code:

  struct Person {
   std::vector<int> values;
   …
  };
  for (auto elem : createPerson().values) { // OK (lifetime extended) <-----------
by introducing a getter to have better encapsulation, suddenly caused the undefined behavior:

  class Person {
   private:
   std::vector<int> values;
   …
   public:
   const auto& getValues() const {
   return values;
   }
  };
  for (auto elem : createPerson().getValues()) { // UB (fatal runtime error)
▲trealira 4 hours ago | parent | prev [-]

Why not simply write the following?

   const Config config { loadConfig() };
   for (auto &name : config.names) {
       use(name);
   }
Or else you could have "loadConfig()" be a method that returns a reference, which is in turn the member of a class, so that there isn't any dangling reference issue.
▲trealira 6 hours ago | parent | prev | next [-]

But that only happens if you fail to learn everything in modern C++. If you want to know everything about C++ inside and out, it seems best to start with learning C inside and out, and then to learn which practices have been superseded by better alternatives in C++ and how C++ has changed them, e.g., how initialization has been complicated.

▲pjmlp 5 hours ago | parent [-]

The problem is that many end up writing C style code in C++ and never bother with best practices, unless they have a proper mentor refusing PR for example.

▲thinkoid 19 minutes ago | parent | prev [-]

It's not a curse, you know. You do not HAVE to bring those practices into C++, only use the learned material to peek under the hood of C++ (not even so, but as the guy above suggested, glimpse into). If only I had a dime for every curmudgeon who took your dogmatic position and tried to scare someone away from C.

There is no better way to understand what's going on in std::vector or std::string than writing a growable array in C and having to keep three facts straight: how much storage you own, how many elements you’re using, and who releases it. Knowing how much work the abstraction does is a damn good reason to use it.

▲sobellian 7 hours ago | parent | prev [-]

It's not expert friendly either. The Stockholm syndrome just kicks in.

▲simonask 4 hours ago | parent | next [-]

Exactly. C++ programmer confidence is a bell curve, where the X axis is skill level.

The more you know about programming in C++, the less confident you become that your code is actually correct, because you've seen before how the most seemingly innocuous decisions turned out to be massive UB footguns. Even worse if you know anything about how computers actually work - that's not relevant, C++ like C targets an abstract virtual machine with semantics unlike any computer ever built.

The simplest example is signed integer overflow: the bright young student knows all about Two's Complement and mistakenly believes all is well, and the wizened but weary mentor must waste everyone's time to avoid summoning nasal demons.

What an unbelievable waste.

▲sedictious 2 hours ago | parent [-]

I'd say C++ is so vast that you can keep on encountering bell curves like that. I start working on a project, building confidence in the subset of C++ I'm working with and when I start feeling good about myself, I'm hit with a completely foreign concept

cppquiz is a nice test beyond "trivia". There are a few hard questions addressing topics I've never encountered. For example:

```

#include <iostream>

volatile int a;

int main() { std::cout << (a + a); }

```

I would assume that here a is initialised to 0 since it has static lifetime so I'd expect this to just print 0. But the C++ standard specifies that:

> Reading an object designated by a volatile glvalue ([basic.lval]), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression (or a subexpression) in general includes both value computations (including determining the identity of an object for glvalue evaluation and fetching a value previously assigned to an object for prvalue evaluation) and initiation of side effects. When a call to a library I/O function returns or an access through a volatile glvalue is evaluated the side effect is considered complete, even though some external actions implied by the call (such as the I/O itself) or by the volatile access may not have completed yet.

and if you have side effects unsequenced relative to other side effects (as is the case with operations of the same operand), this is considered UB

▲0x457 2 hours ago | parent [-]

In practice, it will be 0, assuming no external modification of a. Strictly under standard, its UB.

▲sedictious an hour ago | parent [-]

yes which is exactly why you don't keep those things in mind most of the times. They are mostly academic exercises yet they pop up in your actual code from time to time and you find yourself furiously scratching your head. But my point is that C++ is huge and there is no way any single human can keep the whole standard in their head.

▲bestouff 6 hours ago | parent | prev [-]

The more you know about C++, the less you're confident about how your code will be compiled.

▲simonask 4 hours ago | parent [-]

No I'm sure it will compile. But will it silently corrupt the customer's data 5 years down the line due to a compiler upgrade that suddenly exposed UB in a rarely taken code path? Much less sure.