NHacker Next
  • new
  • past
  • show
  • ask
  • show
  • jobs
  • submit
Understanding Memory Management, Part 2: C++ and RAII (educatedguesswork.org)
williamcotton 10 hours ago [-]
> Everything we've seen here is still normal C, but often we want to associate a function with a type. For instance, the area function we have shown above only works with rectangles, but what if we had circles as well? We'd end up with two functions, one called area_rectangle and one called area_circle.

This is not to call the article into question but only to show that C11 does support generics, allowing for:

  printf("Rectangle area: %.2f\n", area(rect));
  printf("Circle area: %.2f\n", area(circle));
Full code here:

https://gist.github.com/williamcotton/a8f429e891cbba5abfadcc...

npalli 5 hours ago [-]
You haven't demonstrated the capability of Generics though (which C doesn't really have, only a minimal version). For this particular example, C++ does function overloading on parameters which C cannot hence you need this silly Generic macro hack, it is not clear how much of a win it is. Reminds of the saying that C is the most dynamic programming language since it has void*

It is much cleaner in C++ where you don't need to declare two separate functions names like you did.

  #include <iostream>
  #include <cmath>

  struct Rectangle {
      double width;
      double height;
  };

  struct Circle {
      double radius;
  };

  double area(const Rectangle& rect) {
      return rect.width * rect.height;
  }

  double area(const Circle& circle) {
      return M_PI * circle.radius * circle.radius;
  }

  int main() {
      Rectangle rect{5.0, 3.0};
      Circle circle{2.5};

      std::cout << "Rectangle area: " << area(rect) << std::endl;
      std::cout << "Circle area: " << area(circle) << std::endl;
      return 0;
  }
shakna 9 hours ago [-]
Though, bear in mind that _Generic is not generic templating. Highly useful, but it's more of a macro.

You can run into issues with aliased types, or where types of the same size accidentally fall through into the wrong parts of the _Generic selector.

flohofwoe 11 hours ago [-]
> ...many C programs will compile just fine with a C++ compiler

Unfortunately(?) that's only true for C code written in the early 90s or specifically for the common C/C++ subset (which is essentially a subset of both C and C++ based on a non-standard snapshot of C ca 1995).

Since C99, the two languages have diverged enough that C is no longer a subset of C++, and IMHO propagating the idea that there's a 'C subset' in C++ 25 years after the 'schism' is harmful both for C and C++.

Calavar 11 hours ago [-]
Interestingly though, compatibility in the reverse direction has actually gotten better over time. C99 allows variables to be declared at any point in a function. Before C99, the all variables up front rule used to be the single biggest reason that C-style C++ code wouldn't compile under a C compiler.
flohofwoe 10 hours ago [-]
Many C compilers accepted this as non-standard extension already before C99 though (along with winged comments, and `for (int...)`).

There is a lot of useful harmonization happening between the two languages (and mostly from the direction of C++ to C)

From the perspective of a C coder, the one good thing about C++ is that it is basically the testing ground for new potential C features to figure out what works and doesn't work in realworld scenarios before the C standard is polluted too much with the ideas that don't work ;)

pjmlp 10 hours ago [-]
Partially, ISO C++ has been updating the underlying C standard library reference, to the extent it is compatible with C++, C++23 refers to C17 and the upcoming C++26 will refer to C23, standard library that is.

However this is exactly the golden example why guest languages never own the platform (in this case UNIX/POSIX/C trio), and eventually the platform and guest always diverge.

Even though both share the same birthplace, as usual adoption takes different routes.

If one never wants to face this, regardless how many pain points the language owning the platform has, sticking to it always wins out in the long run.

bluGill 9 hours ago [-]
There are people on the C standard commitee with their main goal keep C tompatible with C++. They don't win ever debate but they win many.
pjmlp 8 hours ago [-]
I don't doubt it, unfortunately design by committee has its constraints.

For example, had C kept under control by its authors, maybe even the security story would have been sorted out by now, who knows.

knorker 11 hours ago [-]
I feel like the article is already implying this:

> Despite this, C++ preserves a huge amount of C heritage and many C programs will compile just fine with a C++ compiler

It preserves "a huge amount", not "backwards compatability". "Many" C programs will compile, not "all". Hell, the author didn't even go as far as to say "most".

Also the author says:

> The original version of C++ WAS basically an object oriented version of C ("C with classes") BUT AT THIS POINT it has been around for 40-odd years and so HAS DIVERGED VERY SIGNIFICANTLY

[my emphasis / capitalization]

I'm not sure what point you're making that's not already in the article.

otherayden 9 hours ago [-]
As a CS undergrad who has worked with C and C++ for assignments but generally sucks at it, I needed this article. Thanks so much for sharing!
einpoklum 10 hours ago [-]
I really wish we would adopt the term CADRe intead of RAII:

"Constructor Allocates, Destructor Releases"

is much clearer a phrase than

"Resource Acquisition Is Initialization"

which, in English, can mean any number of things, particularly initialziation that's distinct from construction.

joshuaissac 9 hours ago [-]
Or "constructor acquires, destructor releases". When I learned about RAII for the first time, its meaning was not clear at all from the phrase "resource acquisition is initialization".
einpoklum 3 hours ago [-]
Yes, perhaps that's even better.
tjoff 9 hours ago [-]
Which is the point. RAII is very much not only used for memory nor construction.

Not saying it is a good term, but we are stuck with it and trying to change it to a better one will only make it worse.

einpoklum 10 hours ago [-]
Ironically, this post suffers from excessive C'ism and older-C++'ism.

Specifically, it encourages the use of pointers for passing-by-reference, and when working with class hierarchies. This is inappropriate and overly dangerous; and references (especially const references) should be prefered, or passing-by-value (and utlilization of copy elisions).

The post also suggests people perform raw allocations with `new`. That is also discouraged; see C++ Core Guideline R11. [1]

[1]: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines...

williamcotton 9 hours ago [-]
> Next Up: Smart Pointers

> RAII is a powerful technique but what we've seen so far is only a partial solution. Things are (mostly) fine when working with objects but if we want to work with pointers, as in our Rectangle example, then we need to implement custom copy constructors, copy assignment operators, etc. if we want them to be safe. This is true even if we want to store on object on the heap but have a pointer on the stack. In the next post I'll be covering a technique called "smart pointers" that helps address these problems.

9 hours ago [-]
rewqa 10 hours ago [-]
[flagged]
Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact
Rendered at 22:01:25 GMT+0000 (UTC) with Wasmer Edge.