Latest / CyberSecurity Summary / C++ Memory Management: Write leaner and safer C++ code using proven memory-management techniques
Transcript
- 0:00Speaker 1: Okay, let's unpack this. Imagine your software running right, doing
- 0:04Speaker 1: its thing, but underneath all that, there's this this hidden world,
- 0:09Speaker 1: unseen forces basically running the show. It's the connection between
- 0:12Speaker 1: your code and the computer's memory. Today we're doing a
- 0:15Speaker 1: deep dive into C plus plus memory management. It's fascinating stuff,
- 0:20Speaker 1: but yeah, often pretty intimidating too. We're using Patresea's really
- 0:24Speaker 1: comprehensive book as our guide here. Now. C plus plus
- 0:27Speaker 1: memory Management it can feel like a maze, you know,
- 0:30Speaker 1: full of complex rules, hidden traps. But our mission today
- 0:33Speaker 1: is to give you a shortcut. We want to boil
- 0:35Speaker 1: down the core ideas, point out those pitfalls, and look
- 0:37Speaker 1: at the modern ways of doing things. Hopefully help you
- 0:40Speaker 1: write C plus plus code that's better, safer, more expressive.
- 0:43Speaker 1: Expect some uh aha moments today.
- 0:46Speaker 2: Absolutely becres he has this great skill, doesn't he, Taking
- 0:49Speaker 2: these really dense technical topics and making them feel well,
- 0:52Speaker 2: almost conversational. This book, it's not just rules. It really
- 0:55Speaker 2: explores how C plus plus talks to memory at its heart.
- 0:59Speaker 2: It's quite empowering.
- 1:00Speaker 1: Actually totally agree. So let's start right at the beginning,
- 1:02Speaker 1: the building blocks. What's the absolute most fundamental thing we
- 1:06Speaker 1: need to get our heads around with C plus plus memory.
- 1:10Speaker 2: Well, what's really interesting is how C plus plus even
- 1:12Speaker 2: defines an object. You know, most people think classes.
- 1:16Speaker 1: Strucks, right, yeah, that's what I think.
- 1:18Speaker 2: But in C plus plus AC it's actually much broader.
- 1:21Speaker 2: Even basic types like an int or a float they're
- 1:24Speaker 2: considered objects too.
- 1:25Speaker 1: Wait, really an int is an object? How does that work?
- 1:29Speaker 2: It's about having certain properties to be an object. In
- 1:32Speaker 2: C plus plus FAG, something needs an address in memory,
- 1:36Speaker 2: it needs to take up some space non zero storage
- 1:40Speaker 2: that has a lifetime, maybe a name, definitely a type,
- 1:42Speaker 2: and a storage duration. In fact, you can actually write
- 1:45Speaker 2: static assert sdd dot ice object vint and well it'll
- 1:49Speaker 2: compile just fine. Huh.
- 1:51Speaker 1: Okay, so even a simple nt has all these characteristics.
- 1:53Speaker 1: That's foundational.
- 1:54Speaker 2: It really is understanding that helps make sense of a
- 1:56Speaker 2: lot of other things.
- 1:57Speaker 1: Okay, so everything has its place, it's time and memory.
- 2:00Speaker 1: Speaking of places, pointers they're everywhere in C plus plus
- 2:04Speaker 1: C right, even if the book mentions kind of usingly
- 2:08Speaker 1: that a strict definition is surprisingly hard to come by
- 2:11Speaker 1: in the standard.
- 2:12Speaker 2: Exactly. Pointers are incredibly powerful tools, but that power comes
- 2:17Speaker 2: with risk. Put it arithmetic for example, you can write
- 2:21Speaker 2: it q qles P plus three, no problem. But if
- 2:24Speaker 2: P isn't pointing where you think it is, trouble, big trouble.
- 2:28Speaker 2: Q could point to some arbitrary location. You could cause
- 2:30Speaker 2: serious damage. And the responsibility for managing that power it
- 2:35Speaker 2: always falls back on the C plus plus programmer. Always right.
- 2:38Speaker 1: With great power, it comes great responsibility. As they say, okay,
- 2:42Speaker 1: what about void? I see that sometimes in like lower
- 2:44Speaker 1: level code.
- 2:45Speaker 2: Ah void. Think of it as just a raw memory address.
- 2:48Speaker 2: It tells you where something is, but not what it is.
- 2:51Speaker 2: It has no type information attached. Any other pointer type
- 2:54Speaker 2: can convert to void, but going back the other way
- 2:56Speaker 2: usually needs an explicit cast, basically saying here's a location,
- 3:00Speaker 2: but I make no promises about what's there.
- 3:02Speaker 1: Got it. So beyond just what an object is, let's
- 3:05Speaker 1: talk about its life in memory, lifetime, size, alignment padding.
- 3:11Speaker 1: How does C plus plus manage lifetime?
- 3:14Speaker 2: Lifetime is absolutely key. Automatic objects, the ones usually on
- 3:17Speaker 2: the stack, have very predictable, deterministic lifetimes. They get created,
- 3:21Speaker 2: they go out of scope, Boom, they're destructed. Static objects
- 3:24Speaker 2: live for pretty much the whole program run. But dynamically
- 3:28Speaker 2: allocated objects, the ones you create with new. Their lifetime
- 3:31Speaker 2: is well when your program says so, and that's where
- 3:35Speaker 2: things can go wrong.
- 3:35Speaker 1: Ah okay, So if it's when your program says so,
- 3:38Speaker 1: I'm guessing the classic mistake is forgetting to say it's
- 3:41Speaker 1: over right, forgetting to delete.
- 3:42Speaker 2: That's the number one pitfall. Absolutely, you call new, you
- 3:45Speaker 2: get your object, it's constructor runs. But if you forget delete,
- 3:48Speaker 2: the destructor never runs, and the memory it just leaks away.
- 3:51Speaker 2: Resource leak, memory leak, bad news.
- 3:53Speaker 1: Right. Okay, Now this next bit sounds really interesting. Size
- 3:56Speaker 1: alignment and padding using size isn't always straightforward.
- 3:59Speaker 2: No, so it often surprises people. This is a great
- 4:01Speaker 2: aha moment. Let's take a simple class class X charcis
- 4:05Speaker 2: short S and tn.
- 4:06Speaker 1: Okay, a char a short an int, So like one
- 4:11Speaker 1: by plus two bytes plus four bytes seven bytes.
- 4:13Speaker 2: That's what you'd intuitively think, right, But if you actually
- 4:16Speaker 2: check size of x, you'll probably find it's eight bytes eight.
- 4:19Speaker 1: Where does the extra byte come from?
- 4:20Speaker 2: Comes from? Padding bytes? Compilers often add these invisible bytes
- 4:24Speaker 2: between members, So between C and S there might be
- 4:27Speaker 2: a padding byte between S and N maybe two padding bytes.
- 4:31Speaker 2: Why performance exactly? Performance CPU's access data much more efficiently
- 4:37Speaker 2: when it's aligned on certain boundaries, like a four byte
- 4:39Speaker 2: boundary for an ind So the compiler adds padding to
- 4:42Speaker 2: ensure each member starts at an optimal address.
- 4:45Speaker 1: Okay, that makes sense, But the book also mentions trailing
- 4:48Speaker 1: padding bytes patting at the end of the object.
- 4:50Speaker 2: Why ah, that's specifically for arrays of these objects. Remember,
- 4:53Speaker 2: array elements have to sit right next to each other
- 4:56Speaker 2: in memory contiguously. That trailing padding ensures that if array
- 4:59Speaker 2: is properly aligned, then R one will also start on
- 5:02Speaker 2: the correct alignment boundary, and so on. It's subtle, but
- 5:05Speaker 2: crucial for array correctness and performance.
- 5:08Speaker 1: Wow. Okay, so memory isn't quite as packed as you
- 5:11Speaker 1: might think. This has got to affect how C plus
- 5:13Speaker 1: plus copies and moves objects around.
- 5:15Speaker 2: Surely, Oh, absolutely, Copy and move operations constructors assignment operators
- 5:20Speaker 2: are deeply affected by this, especially when you write your
- 5:23Speaker 2: own classes. For a really simple struct maybe like point
- 5:27Speaker 2: two d just two floats, the compiler generated copy and
- 5:31Speaker 2: move are usually fine, But if you have a class
- 5:33Speaker 2: like say naive string, that manages its own raw memory
- 5:36Speaker 2: like a character array, then the defaults are not. Okay,
- 5:39Speaker 2: you absolutely need to write your own destructor copy constructor
- 5:42Speaker 2: copy assignment. That's the classic rule of three and.
- 5:45Speaker 1: The rule of five. If you add move operations, which
- 5:47Speaker 1: is pretty standard now in modern C plus.
- 5:50Speaker 2: Plus, precisely you need custom logic to handle copying or
- 5:54Speaker 2: moving that raw memory correctly, Otherwise you end up with
- 5:56Speaker 2: shallow copies, double deletes all sorts of problems.
- 5:58Speaker 1: And the book mentions s TD dot exchange as a
- 6:01Speaker 1: helper for writing move constructors.
- 6:03Speaker 2: Yeah, std dot exchange is neat little utility. It basically
- 6:07Speaker 2: lets you swap the resource pointer in your move constructor.
- 6:09Speaker 2: More cleanly, it assigns a new value like null ptr
- 6:13Speaker 2: to the source objects pointer and gives you back the
- 6:15Speaker 2: old value the resource pointer, all in one go. Makes
- 6:18Speaker 2: the code a bit tidier less error prone.
- 6:21Speaker 1: Okay, and while we're on data layout, what about basic
- 6:24Speaker 1: built in arrays raw rays? They're just sequences in memory, right,
- 6:27Speaker 1: and pointer arithmetic is key there too, Exactly.
- 6:30Speaker 2: Raw rays are contiguous sequences, and accessing RA is basically
- 6:34Speaker 2: the same as writing R plus I. The crucial thing
- 6:37Speaker 2: is that the plus i isn't just adding ie bytes.
- 6:40Speaker 2: It's typed. It means add i times the size of
- 6:43Speaker 2: one element. So if it's an array events, it adds
- 6:45Speaker 2: i size of bytes. That's how it steps correctly from
- 6:48Speaker 2: one element to the next.
- 6:49Speaker 1: Right, it knows the size of the things in the
- 6:51Speaker 1: array precisely.
- 6:52Speaker 2: Oh. In an interesting side note, new and darro is
- 6:54Speaker 2: actually allowed, you can dynamically allocate a zero sized array.
- 6:58Speaker 2: Doesn't sound useful, but it can simple some generic code sometimes.
- 7:01Speaker 1: Okay, we've got the building blocks. Now let's walk down
- 7:04Speaker 1: what the book calls the perilous path things to be
- 7:08Speaker 1: really careful with. It talks about different kinds of evil
- 7:11Speaker 1: in C plus plus. What let's start with. IFNDR sounds ominous.
- 7:16Speaker 2: IFNDR ill formed no diagnostic required, it's insidious. It means
- 7:21Speaker 2: your code is technically broken according to the C plus
- 7:23Speaker 2: plus standard, but the compiler isn't actually required to warn
- 7:26Speaker 2: you about it.
- 7:27Speaker 1: So it might compile fine, but just not work, or
- 7:30Speaker 1: work sometimes.
- 7:31Speaker 2: Exactly silent failures really hard to debug. The compiler might
- 7:36Speaker 2: not have enough info compile time, or the standard just
- 7:38Speaker 2: gives it a pass on issuing a diagnostic. Very dangerous, okay.
- 7:42Speaker 1: And then the big one, undefined behavior UB everyone talks
- 7:45Speaker 1: about ub ah.
- 7:46Speaker 2: Yes, UB undefined behavior means the C plus plus standard
- 7:50Speaker 2: places absolutely no requirement on what happens if your code
- 7:53Speaker 2: triggers it. Anything could happen. It might crash, it might
- 7:56Speaker 2: give the wrong answer, it might format your hard drive. Okay,
- 7:59Speaker 2: probably not that last one, but technically the standard doesn't
- 8:02Speaker 2: forbid it.
- 8:02Speaker 1: So like dear referencing a null pointer or using an
- 8:05Speaker 1: uninitialized variable, those are.
- 8:07Speaker 2: The classic examples. Yes, dear referencing null, using uninitialized memory,
- 8:12Speaker 2: accessing a raise out of bounds, signed integer overflow. The
- 8:16Speaker 2: list goes on. If you hit UB, you are in
- 8:19Speaker 2: serious trouble. As the book puts it, all bets are off.
- 8:21Speaker 1: And the scary part is how compilers treat it. Right,
- 8:24Speaker 1: they optimize around it.
- 8:25Speaker 2: That's the really unsettling part. Compilers assume that correct C
- 8:28Speaker 2: plus plus code never contains UB, so if they see
- 8:31Speaker 2: potentially UB, they might just optimize assuming it can't happen.
- 8:34Speaker 2: They might remove null checks because hey, you wouldn't dare
- 8:37Speaker 2: reference null later, right. They might reorder operations or eliminate
- 8:41Speaker 2: entire loops based on assumptions flowing from potentially UB. It
- 8:44Speaker 2: leads to sometimes surprising effects.
- 8:46Speaker 1: To put it mildly, wow, So UB isn't just It
- 8:49Speaker 1: might crash. It's the compiler might silently break my code
- 8:52Speaker 1: in weird ways.
- 8:53Speaker 2: Precisely treat you b as a critical bug. Always don't
- 8:56Speaker 2: rely on it working on your specific compiler version.
- 8:58Speaker 1: Okay, IFNDR, what about the one definition rule the ODR.
- 9:03Speaker 1: That sounds important, but maybe less evil.
- 9:05Speaker 2: The ODR is crucial, but yeah, maybe less overtly evil,
- 9:10Speaker 2: more subtly problematic if violated. It basically says that anything
- 9:15Speaker 2: in your program, a function, a class, a template, a
- 9:18Speaker 2: global variable must have exactly one definition in the entire program.
- 9:23Speaker 1: And if you have two definitions, say in different.
- 9:25Speaker 2: Files, then you're often in IFNDR territory again, or the
- 9:29Speaker 2: linker might just silently pick one definition and ignore the other.
- 9:33Speaker 2: This can lead to absolute chaos, especially with templates or
- 9:36Speaker 2: inline functions defined slightly differently in headers included in different places,
- 9:41Speaker 2: very hard to track down bugs.
- 9:42Speaker 1: And implementation defined behavior. How does that fit in?
- 9:45Speaker 2: That's different? Implementation defined means the standard allows different behaviors,
- 9:50Speaker 2: but requires the compiler vendor to document exactly what their
- 9:53Speaker 2: implementation does.
- 9:54Speaker 1: So it's predictable on one compiler, but maybe not portable.
- 9:57Speaker 2: Exactly, Like the size of NT or the result of
- 9:59Speaker 2: right fifting a negative number. It's not inherently evil, just
- 10:02Speaker 2: something to be aware of if you need your code
- 10:04Speaker 2: to work identically everywhere.
- 10:05Speaker 1: Okay, moving on to specific dangerous things point or maneuvers
- 10:10Speaker 1: beyond just adding random numbers. The book mentions type punning.
- 10:15Speaker 2: What's that type punning? It's essentially trying to subvert the
- 10:19Speaker 2: type system. As the book says, you have memory representing
- 10:22Speaker 2: one type, say a float, and you try to access
- 10:24Speaker 2: it as if it were a different type, say an int,
- 10:27Speaker 2: to reinterpret its raw bits.
- 10:30Speaker 1: How do people usually try to do this?
- 10:32Speaker 2: A common but usually illegal way in C plus plus
- 10:35Speaker 2: plus S is using a union. You have a union
- 10:38Speaker 2: with maybe float F and an N you're at to UDAF.
- 10:41Speaker 2: Then you immediately try to read you in.
- 10:43Speaker 1: And that's ub even though they share the same memory.
- 10:45Speaker 2: Generally, yes, that's UBN C plus plus here. Reading from
- 10:48Speaker 2: a union member that wasn't the last one written to
- 10:50Speaker 2: is undefined unless you're dealing with what's called the common
- 10:53Speaker 2: initial sequence.
- 10:54Speaker 1: Common initial sequence.
- 10:55Speaker 2: Yeah, it's a narrow exception. If two structs or classes
- 10:58Speaker 2: in the union start with the same sequence of men
- 11:00Speaker 2: types like both start with an innt followed by a char.
- 11:02Speaker 2: You can write to one and then read that common
- 11:04Speaker 2: sequence part through the other, but it's complex. Relying on
- 11:07Speaker 2: union penning is usually asking for trouble.
- 11:10Speaker 1: What about using std dot memppi. I've seen that used
- 11:13Speaker 1: for reinterpreting.
- 11:14Speaker 2: Bits, right, mechpapie is often suggested. It can be used,
- 11:18Speaker 2: but you have to be careful. If you mempi the
- 11:20Speaker 2: bytes of a float into some raw memory buffer and
- 11:22Speaker 2: then immediately try to read that buffer using an INT,
- 11:25Speaker 2: that's still you b why because mechpi doesn't magically start
- 11:28Speaker 2: the lifetime of nnt object there. It might start the
- 11:30Speaker 2: lifetime of a float if the conditions are right, but
- 11:33Speaker 2: accessing it via ND violates type rules.
- 11:36Speaker 1: So how do you use megpi correctly for this?
- 11:39Speaker 2: The safe way is to magpie the bytes into an
- 11:41Speaker 2: already existing object of the target type, so you'd have
- 11:44Speaker 2: an invariable already and you may compile the float's bites
- 11:46Speaker 2: into the memory location of that INT. That's generally okay.
- 11:49Speaker 1: This is getting really low level. Are there specific types
- 11:52Speaker 1: for messing with addresses as numbers?
- 11:54Speaker 2: Yes, C plus plus provides std dot ntptr t and
- 11:58Speaker 2: ftd dot untptr. These are integer types guaranteed to be
- 12:02Speaker 2: large enough to hold a pointer value. You can cast
- 12:04Speaker 2: a pointer to one of these, do some integer math, maybe,
- 12:06Speaker 2: and then cast it back, But the book warns they
- 12:09Speaker 2: are inherently fragile and non portable. Things like bait order
- 12:13Speaker 2: indianness can bite you. If you're storing addresses as integers,
- 12:18Speaker 2: you're really operating outside the safety of the type system.
- 12:21Speaker 2: Use with extreme caution, usually only needed for very specific,
- 12:25Speaker 2: low level tasks.
- 12:26Speaker 1: Right, Okay, we've seen the dangers. Let's talk about tools
- 12:30Speaker 1: for control. Casting spells as the book calls them. How
- 12:33Speaker 1: should we think about casts? Are we lying to the compiler?
- 12:37Speaker 2: That's a common misconception. Yeah, It's better to think of
- 12:39Speaker 2: casts not as lying, but as adjusting the compiler's view.
- 12:44Speaker 2: You're explicitly telling the compiler. I know you see this
- 12:46Speaker 2: expression as type A, but I want you to treat
- 12:49Speaker 2: it as type B for this specific operation. You're signaling
- 12:52Speaker 2: your intent.
- 12:52Speaker 1: Okay, makes sense. Let's go through the C plus plus
- 12:55Speaker 1: name casts. First. Stato cast. The book calls it our
- 12:58Speaker 1: best friend.
- 12:59Speaker 2: And for good reason. Static cast is for well defined
- 13:02Speaker 2: or reasonably safe conversions things the compiler could often do
- 13:05Speaker 2: implicitly or standard conversions between related types like in to
- 13:09Speaker 2: float or importantly, casting a pointer from a drive class
- 13:13Speaker 2: to its public base class drive it base.
- 13:15Speaker 1: Does stato caast ever change the actual memory address?
- 13:19Speaker 2: Yes, it can. That's a key point. Ye. If use
- 13:21Speaker 2: static cast to drive to a base in a multiple
- 13:23Speaker 2: inheritance scenario, the address might actually change. The base subobject
- 13:28Speaker 2: might not be located at the very beginning of the
- 13:30Speaker 2: drived object and memory. Stata cast handles that address adjustment correctly.
- 13:34Speaker 1: Okay, next dynamic cast, the book says it's assigned. Something's wrong.
- 13:39Speaker 1: That's pretty strong.
- 13:40Speaker 2: It often is assigned. Yeah. Yeah. Dynamic cast is used
- 13:43Speaker 2: for navigating class hierarchies at runtime, typically casting down from
- 13:47Speaker 2: a bates class point of reference to a drive class
- 13:49Speaker 2: point of reference. It needs run time type information RTTI enabled,
- 13:53Speaker 2: which adds overhead, and if the cast fails because the
- 13:57Speaker 2: object isn't actually of the target drive type, it returns
- 14:00Speaker 2: null ptr for pointers or throws std dot bad cast
- 14:04Speaker 2: for references.
- 14:05Speaker 1: So why is it assigned? Something's wrong?
- 14:06Speaker 2: Because heavy reliance on dynamic cast often suggests your class
- 14:09Speaker 2: design might be flawed. You might be better off using
- 14:12Speaker 2: virtual functions polymorphism to achieve the desired behavior without needing
- 14:16Speaker 2: to know the exact drived type at runtime. The book
- 14:18Speaker 2: suggests its use implies a potentially perfectible interface.
- 14:22Speaker 1: Got it, then const cast playing tricks with safety.
- 14:26Speaker 2: Yeah. Constcast is the only cast that can remove cost
- 14:30Speaker 2: or volatile. Its main legitimate use is often dealing with
- 14:34Speaker 2: older APIs or libraries that weren't const correct. You might
- 14:39Speaker 2: have a const object but need to pass it to
- 14:40Speaker 2: a function that inexplicably takes a non constant pointer, even
- 14:44Speaker 2: though you know the function won't actually modify it. But
- 14:46Speaker 2: it's dangerous, extremely dangerous if misused. If the object you're
- 14:50Speaker 2: casting away consts from was originally declared as cost, then
- 14:54Speaker 2: actually trying to modify it through the constcast at pointer
- 14:57Speaker 2: is undefined behavior. You're breaking a fundamental primt use it very,
- 15:01Speaker 2: very sparingly.
- 15:02Speaker 1: And finally, the most feared one reinterpret cast. Believe me
- 15:06Speaker 1: a compiler.
- 15:07Speaker 2: That sums it up perfectly. Reinterpret cast does a raw
- 15:09Speaker 2: bit level reinterpretation between pointer types or pointers and integers.
- 15:13Speaker 2: It tails a compiler forget types. Just treat these bits
- 15:16Speaker 2: as if they were this other pointer type m key danger.
- 15:19Speaker 2: It does no address adjustments. Remember how static cast might
- 15:23Speaker 2: adjust the address for base classes. Reinterpret cast doesn't, so.
- 15:26Speaker 1: If you reinterpret cast a derived to a base in
- 15:28Speaker 1: multiple inheritance, you'll.
- 15:30Speaker 2: Likely get the wrong addressed for the base subobject, and
- 15:33Speaker 2: trying to use that pointer leads straight to undefined behavior.
- 15:37Speaker 2: It's incredibly powerful for low level bit manipulation, but incredibly
- 15:41Speaker 2: easy to misuse with disastrous consequences. Only use it if
- 15:45Speaker 2: you absolutely know what you're doing at the bit level.
- 15:48Speaker 1: Any other is worth mentioning quickly.
- 15:49Speaker 2: The book also notes STD dot bitcast from C plus
- 15:53Speaker 2: plus twenty, which is a safer way to do the
- 15:55Speaker 2: type punting reinterpretation for object types copying bits safely, and
- 16:00Speaker 2: STD do duration cast for working with chronotime durations, which
- 16:03Speaker 2: is very useful and safe.
- 16:04Speaker 1: Okay, And the last cast, the reviled one, the C
- 16:08Speaker 1: style cast TX a prick. Why is it so bad
- 16:11Speaker 1: in C plus.
- 16:12Speaker 2: Plus h several reasons. One, it's hard to search foreign
- 16:15Speaker 2: coode compared to the name C plus plus casts, two,
- 16:18Speaker 2: and most importantly, it lacks intent. A C style cast
- 16:22Speaker 2: tries to be smart and will attempt to sequence of conversions,
- 16:25Speaker 2: often ending up doing a stata cast, a costcast, or
- 16:28Speaker 2: even a reinterpret cast, depending on the types involved.
- 16:31Speaker 1: So am I do a dangerous reinterpret cast when you
- 16:33Speaker 1: didn't explicitly mean.
- 16:34Speaker 2: It to exactly? It hides the potential danger. Using the
- 16:38Speaker 2: specific C plus plus casts forced you to think about
- 16:41Speaker 2: what kind of conversion you actually need and makes your
- 16:44Speaker 2: intent clear to other readers and your future self. Avoid
- 16:47Speaker 2: C style casts in modern C.
- 16:49Speaker 1: Plus plus right clear intent is key. Okay, we've seen
- 16:52Speaker 1: the tools the dangers. Now let's talk about taking responsibility
- 16:56Speaker 1: C plus plus style RAII and smart pointers. The book
- 17:00Speaker 1: really emphasizes the power of destructors here.
- 17:03Speaker 2: Destructors are arguably the killer feature of C plus plus
- 17:06Speaker 2: for resource management. They enable RAII. Resource acquisition is initialization,
- 17:12Speaker 2: though as the book chekily points out, the name is
- 17:14Speaker 2: a bit misleading. It's really more to do with destructors
- 17:16Speaker 2: than constructors. How So, the core idea is you acquire
- 17:20Speaker 2: a resource like memory, a file handle, a lock in
- 17:23Speaker 2: an object's constructor. That object now owns the resource. When
- 17:27Speaker 2: the object's light time ends, usually when it goes out
- 17:29Speaker 2: of scope, its destructor is automatically called, and the destructor's
- 17:32Speaker 2: job is to release the resource.
- 17:34Speaker 1: Ah. So acquisition is tied to object initialization, but the
- 17:37Speaker 1: magic happens at destruction.
- 17:39Speaker 2: Precisely. This automatic cleanup is why some C plus plus luminaries,
- 17:44Speaker 2: as the book calls them, say, the most beautiful instruction
- 17:47Speaker 2: in C plus plus is the closing brace that marks
- 17:50Speaker 2: the end of a scope triggering destructors.
- 17:52Speaker 1: Because it guarantees cleanup even if errors happen exactly.
- 17:56Speaker 2: RAII makes code naturally exception safe. If an exception is thrown,
- 18:01Speaker 2: the stack on wines, scopes are exited, and the destructors
- 18:04Speaker 2: of local objects are still called, ensuring resources aren't leaked.
- 18:08Speaker 2: It's incredibly powerful and robust.
- 18:10Speaker 1: This leads perfectly into smart pointers, doesn't it. Raw pointers,
- 18:13Speaker 1: as we said, don't convey ownership clearly who's responsible for
- 18:17Speaker 1: the delete.
- 18:17Speaker 2: That's the fundamental problem raw pointers pose for resource management.
- 18:21Speaker 2: Smart pointers solve this by encoding ownership semantics directly into
- 18:24Speaker 2: the type system. They wrap a raw pointer and manage
- 18:27Speaker 2: its lifetime according to specific rules.
- 18:29Speaker 1: Let's start with std dot unique ftr std.
- 18:32Speaker 2: Dot UNIQFTR represents exclusive ownership. It's the single clear last
- 18:37Speaker 2: user of a resource. Only one unique FTR can own
- 18:41Speaker 2: a particular object at any time. It's very lightweight, typically
- 18:44Speaker 2: the same size as a raw pointer. Zero runtime overhead Crucially,
- 18:48Speaker 2: it's noncopyable. You can move ownership from one uniquapture to another,
- 18:51Speaker 2: but you can't have two pointing to the same resource, so.
- 18:54Speaker 1: It enforces that single owner idea.
- 18:56Speaker 2: What else it handles a raise correctly if you use
- 18:59Speaker 2: unique toture, and you can provide custom deleters if the
- 19:02Speaker 2: resource isn't managed by a simple delete like closing a
- 19:04Speaker 2: file handle. It's generally your first choice for managing dynamic memory.
- 19:07Speaker 1: Okay, exclusive ownership, what if you need shared ownership?
- 19:11Speaker 2: That's where std dot shared GTR comes in. It's designed
- 19:14Speaker 2: for scenarios where multiple parts of your code need to
- 19:16Speaker 2: share ownership of a resource and the last owner is
- 19:19Speaker 2: not known a priori think complex data structures or maybe
- 19:23Speaker 2: asynchronous callbacks.
- 19:24Speaker 1: How does it manage that?
- 19:26Speaker 2: It uses reference counting internally. It keeps track of how
- 19:29Speaker 2: many shared ptr instances are currently pointing to the same
- 19:32Speaker 2: resource via a shared control block. When a shared ptr
- 19:36Speaker 2: is copied, the count goes up. When a shared PDR
- 19:39Speaker 2: is destroyed or reset, the count goes down. When the
- 19:41Speaker 2: count reaches zero, the resource is automatically deleted.
- 19:45Speaker 1: That sounds like it has more overhead than unique curtio.
- 19:47Speaker 2: It does size of shared ptrt is larger than size
- 19:50Speaker 2: of dqrt because it needs space for the pointer to
- 19:52Speaker 2: the resource and a pointer to the control block. There's
- 19:55Speaker 2: also the atomic overhead of incrementing and decrementing the reference count,
- 20:00Speaker 2: which matters in multi threaded code, so you use it
- 20:03Speaker 2: when you truly need shared ownership semantics.
- 20:05Speaker 1: And for creating shared PTRs, the book strongly recommends sdd
- 20:09Speaker 1: dot make shared. There's a performance reason for that, right
- 20:12Speaker 1: and a huh yeah.
- 20:13Speaker 2: Absolutely avoid doing shared ptrt. Always prefer std dot make
- 20:17Speaker 2: shared T. The AHA moment is this, make shared performs
- 20:21Speaker 2: a single memory allocation that holds both the object T
- 20:24Speaker 2: and its control block together.
- 20:25Speaker 1: Whereas new T followed by the shared ptr constructor does
- 20:28Speaker 1: two separate allocations.
- 20:30Speaker 2: It's exactly two allocations, means more overhead, potentially worse cash locality,
- 20:34Speaker 2: The object in its counter might be far apart in memory,
- 20:37Speaker 2: and critically a potential leak risk. Oh So imagine f
- 20:41Speaker 2: shared ptrkeg. If G throws an exception after new T succeeds,
- 20:45Speaker 2: but before the shared ptr constructor takes ownership, the newly
- 20:49Speaker 2: allocated T object is leaked Forever. Make shared avoids this
- 20:52Speaker 2: by doing the allocation and construction in a safer combined.
- 20:55Speaker 1: Step clever, Okay, one more smart cooiner std dot weakptr.
- 20:59Speaker 1: It's ones less useful, not.
- 21:02Speaker 2: Less useful, just different. Std dot weekptr is a companion
- 21:05Speaker 2: to std dot shared ptr. It holds a non owning
- 21:08Speaker 2: reference to an object managed by shared ptr. It observes
- 21:11Speaker 2: the object but doesn't affect its reference count. You can
- 21:13Speaker 2: try to lock a weekptr to get a temporary shared
- 21:15Speaker 2: ptr if the object still exists.
- 21:17Speaker 1: What's the main use case?
- 21:18Speaker 2: The absolute killer use case is breaking cycles. If you
- 21:22Speaker 2: have two objects that hold shared PDRs to each other,
- 21:25Speaker 2: they create a reference cycle. The reference counts will never
- 21:28Speaker 2: drop to zero even when all external shared PDRs are
- 21:31Speaker 2: gone memory leak. By having one object hold a weekpdr
- 21:35Speaker 2: to the other, you break the cycle, allowing them to
- 21:37Speaker 2: be destroyed correctly. It's essential for implementing caches or observer
- 21:41Speaker 2: patterns safely with shared.
- 21:42Speaker 1: Pdr right breaking those ownership loops. Okay, we've covered the
- 21:46Speaker 1: standard tools. Let's go beyond the standard customization performance overloading
- 21:50Speaker 1: memory allocation operators.
- 21:52Speaker 2: Yes, C plus plus gives you the power to completely
- 21:56Speaker 2: replace the default memory allocation functions. Operator new and operator delete.
- 22:01Speaker 2: You can provide global overrides or member function overrides for
- 22:04Speaker 2: specific classes.
- 22:05Speaker 1: Why would you do that?
- 22:06Speaker 2: Performance custom memory tracking using specialized allocators like pool allocators arenas.
- 22:12Speaker 2: But as the book says, great power comes great responsibility.
- 22:16Speaker 2: If you override these, you're the memory manager. Small mistates
- 22:19Speaker 2: can have a huge impact, causing leaks, corruption, or performance degradation.
- 22:23Speaker 1: Okay, so it's advanced stuff. What about placement new. The
- 22:27Speaker 1: book calls it the most important version of operator new.
- 22:30Speaker 2: Why because placement new doesn't actually allocate memory. Its signature
- 22:34Speaker 2: looks like void operator newstd dot size void ptr. It
- 22:39Speaker 2: takes a size and a pre allocated pointer ptr, and
- 22:42Speaker 2: it simply returns that same pointer ptr.
- 22:44Speaker 1: So what's the point.
- 22:46Speaker 2: Its point is to construct an object at a specific
- 22:49Speaker 2: memory location that you've already obtained. Somehow, it decouples allocation
- 22:52Speaker 2: from construction.
- 22:53Speaker 1: And where is that useful?
- 22:54Speaker 2: Several places mapping C plus plus objects directly onto memory.
- 22:58Speaker 2: MAPP hardware registers implementing custom containers that pre allocate large
- 23:02Speaker 2: chunks of memory and then use placement new to construct
- 23:05Speaker 2: objects within that chunk as needed, much faster than allocating
- 23:08Speaker 2: each object individually. And it's key for optimizations like small
- 23:12Speaker 2: object optimization SOO or small string optimization SSO. In std
- 23:18Speaker 2: dot function or std dot string, they might use internal
- 23:21Speaker 2: buffer space and placement new for small object strings, avoiding
- 23:24Speaker 2: heap allocation entirely.
- 23:25Speaker 1: That makes sense, decoupling allocation and construction. The book even
- 23:29Speaker 1: walks through writing a simple leak detector using operator overloading.
- 23:33Speaker 2: Yes, a great practical example. Yeah, you overload global new
- 23:36Speaker 2: and delete. In new, you allocate a bit extra memory,
- 23:40Speaker 2: store the requested size and that extra bit at the beginning,
- 23:43Speaker 2: and return a pointer just past that hidden size info.
- 23:46Speaker 1: That's the lie it mentions, hiding the size exactly.
- 23:50Speaker 2: Then in your overloaded delead you take the user's pointer
- 23:53Speaker 2: back up slightly to read the hidden size, record that
- 23:56Speaker 2: this block is now free, and then deallocate the entire blode,
- 24:00Speaker 2: including the hidden size. You use some central accountant object
- 24:04Speaker 2: to track what's allocated versus.
- 24:05Speaker 1: Freed, and it uses the Meyer's singleton for that accountant.
- 24:09Speaker 1: What's the catch there and the alignment issue?
- 24:11Speaker 2: Right? The Meyer singleton uses a static local variable inside
- 24:15Speaker 2: of function to ensure only one instance of the accountant
- 24:18Speaker 2: is created, and it's done in a thread safe way.
- 24:20Speaker 2: In modern c plus plus thanks to magic statics doing
- 24:23Speaker 2: implicit syncretization. The catch is that this synchronization can add
- 24:27Speaker 2: a small performance overhead. The critical pitfall, though, is alignment.
- 24:32Speaker 2: If you just store size it for the size, what
- 24:35Speaker 2: if the object being allocated needs stricter alignment than size it,
- 24:38Speaker 2: like an object needing sixteen by alignment, Your hidden size
- 24:41Speaker 2: might throw off the alignment of the object itself.
- 24:44Speaker 1: Out serious trouble. How do you fix that?
- 24:46Speaker 2: The fix is clever. You allocate enough space at the start,
- 24:49Speaker 2: not just for size it, but for std do maxiligned
- 24:52Speaker 2: This type guarantees alignment suitable for any standard type. You
- 24:56Speaker 2: store your size within that maxiline space and then return
- 24:59Speaker 2: the pointer. After that guaranteed alignment boundary, you jump over
- 25:03Speaker 2: the metadata space, ensuring the user's object is correctly aligned.
- 25:06Speaker 1: Very neat, okay, moving faster now. Arena based memory management
- 25:10Speaker 1: sounds fast.
- 25:11Speaker 2: It could be blazingly fast. The idea is simple. Allocate
- 25:14Speaker 2: one huge chunk of memory up front the arena. Then
- 25:18Speaker 2: your custom operator new just bumps a pointer within that
- 25:21Speaker 2: arena to hand out memory. A delete might do nothing
- 25:25Speaker 2: at all. Nothing Often Yeah, you just use the arena
- 25:28Speaker 2: for a specific phase like loading a game level, processing
- 25:31Speaker 2: a request, and when you're done, you discard the entire
- 25:34Speaker 2: arena in one go. Allocation becomes just pointer edition deallocation
- 25:38Speaker 2: becomes a no op until the end. Super fast, minimal
- 25:42Speaker 2: fragmentation within the arena.
- 25:44Speaker 1: Where is this used?
- 25:45Speaker 2: Games are a classic example. Memory po level or seam
- 25:48Speaker 2: high performance servers, memory per request compilers anywhere you have
- 25:52Speaker 2: predictable phases of allocation and deallocation.
- 25:54Speaker 1: And the performance numbers are impressive.
- 25:56Speaker 2: The book site's examples showing custom new taking maybe seventy
- 25:59Speaker 2: five percent of the time I'm a standard new, and
- 26:01Speaker 2: custom delete being a tiny fraction like eight percent of
- 26:03Speaker 2: the time of standard delete because it often does nothing.
- 26:06Speaker 2: Huge gains possible if the pattern.
- 26:07Speaker 1: Fits and chunked pools are related.
- 26:10Speaker 2: Kind of an extension. Instead of one big arena for anything,
- 26:13Speaker 2: you might have multiple pools, each managing fixed sized chunks
- 26:16Speaker 2: of memory. Eg. A pool for thirty two byte objects,
- 26:19Speaker 2: one for sixty four byte, et cetera. When you need
- 26:22Speaker 2: an object of a certain size, you grab a pre
- 26:24Speaker 2: allocated block from the corresponding pool. Very efficient for allocating
- 26:28Speaker 2: many objects of a few common sizes.
- 26:30Speaker 1: Okay, powerful stuff. Now let's look at the bleeding edge.
- 26:33Speaker 1: C plus plus keeps evolving. C plus plus twenty three
- 26:37Speaker 1: just landed. C plus plus twenty six, C plus plus
- 26:39Speaker 1: twenty nine are coming. What's new in memory management?
- 26:42Speaker 2: Right? The language doesn't stand still. These newer features often
- 26:45Speaker 2: address long standing tricky problems or enable new optimizations. A
- 26:48Speaker 2: big one in C plus plus twenty three is std
- 26:52Speaker 2: dot start.
- 26:52Speaker 1: Lifetimess what problem needed solving there.
- 26:55Speaker 2: Imagine reading raw bytes from a network socket or a
- 26:57Speaker 2: file into a SHAR buffer or std dot com byte buffer.
- 27:00Speaker 2: You know those bytes represents a my packet strucked, but
- 27:04Speaker 2: the C plus plus compiler doesn't. Officially no, mypacket object's
- 27:08Speaker 2: lifetime has begun in that buffer.
- 27:10Speaker 1: So just casting the buffer pointer to my packet is.
- 27:12Speaker 2: Technically undefined behavior. It might seem to work by luck
- 27:16Speaker 2: on your compiler, but it's not guaranteed or portable. STD
- 27:20Speaker 2: dot start lifetime is my packet buffer ptr is the fix.
- 27:24Speaker 2: It's like a magical no op function that doesn't generate code.
- 27:28Speaker 2: What tells the compiler trust me, the lifetime of a
- 27:32Speaker 2: mypacket object has now implicitly started at this location.
- 27:35Speaker 1: AH, so it makes it common. Pattern is safe and
- 27:38Speaker 1: portable that sounds like a huge relief for network programmers.
- 27:41Speaker 2: Absolutely, the book calls it a potential boon to network
- 27:43Speaker 2: programmers everywhere and anyone reading binary data. It closes a
- 27:47Speaker 2: long standing ub loople.
- 27:49Speaker 1: Okay, C plus plus twenty six mentions. Trivial relocation that
- 27:52Speaker 1: sounds like an optimization.
- 27:53Speaker 2: It's a potentially huge optimization. Normally, moving an object means
- 27:57Speaker 2: copy constructing it at the destination and then destructing it
- 28:00Speaker 2: at the source. Even with move semantics, there's still a
- 28:03Speaker 2: copy of members and a destroy. Trivial relocation applies to
- 28:07Speaker 2: types where moving them is equivalent to just doing a
- 28:10Speaker 2: mebcapie of their bytes and leaving the source memory uninitialized.
- 28:13Speaker 2: No constructor or destructor calls needed for the move itself.
- 28:16Speaker 1: So for types like std dot vectorant, maybe moving it
- 28:20Speaker 1: could just copy the pointer size and capacity bytes.
- 28:23Speaker 2: Potentially Yes, If a type like maybe std dot uniquipdr
- 28:27Speaker 2: or simple pod like structs or potentially containers under the
- 28:30Speaker 2: right conditions is deemed trivially relocatable, the compiler can optimize
- 28:35Speaker 2: moves down to a raw memory.
- 28:36Speaker 1: Copy and the bed part.
- 28:38Speaker 2: The best part, as the book highlights, is that existing
- 28:41Speaker 2: code using std dot mob on these types compiled with
- 28:44Speaker 2: previous standards could just run faster without changing a single
- 28:47Speaker 2: line of source code when recompiled with a C plus
- 28:50Speaker 2: plus twenty six compiler that implements this free performance.
- 28:53Speaker 1: Nice okay, last one type of ware allocation and de
- 28:56Speaker 1: allocation functions. What's this about?
- 28:58Speaker 2: This is a really interesting propose. It allows overloading operator
- 29:01Speaker 2: new and operator delete to take an extra argument STD
- 29:05Speaker 2: dot type identity T, so.
- 29:07Speaker 1: The allocator function itself knows the type of the object
- 29:09Speaker 1: being allocated exactly.
- 29:12Speaker 2: Currently, global operator new just gets a size request. It
- 29:15Speaker 2: doesn't know if you're allocating an int, a STD dot string,
- 29:18Speaker 2: or a huge custom class. With type awareness, the allocation
- 29:22Speaker 2: function could potentially use different strategies based on the type T.
- 29:25Speaker 2: Maybe allocate small objects from one pool, large objects from another,
- 29:29Speaker 2: or objects of a specific class known to benefit from
- 29:32Speaker 2: a certain memory layout from a dedicated arena.
- 29:35Speaker 1: So it could integrate some of those custom arena pool
- 29:37Speaker 1: benefits directly into the global allocation mechanism guided by type.
- 29:41Speaker 2: That's the idea. It opens up new avenues for optimizations
- 29:44Speaker 2: based on type information, potentially making customized allocation strategies easier
- 29:48Speaker 2: to implement and integrate system wide. It's a really forward
- 29:51Speaker 2: looking concept.
- 29:52Speaker 1: Wow. Okay, we've really gone from the absolute fundamentals like
- 29:55Speaker 1: an int being an object, all the way through the
- 29:57Speaker 1: weeds of UGB, the elegance OFRIII and smart pointers, custom allocators,
- 30:03Speaker 1: and now these cutting edge C plus plus twenty three
- 30:05Speaker 1: twenty six features. It's amazing how much depth there is
- 30:08Speaker 1: to C plus plus memory management and how Patresea's book
- 30:12Speaker 1: lays it all out. It really gives you a sense
- 30:13Speaker 1: of how the software connects to the actual machine.
- 30:16Speaker 2: It really does. Yeah, and understating this stuff, even if
- 30:18Speaker 2: you don't write C plus plus every day, it's incredibly valuable.
- 30:22Speaker 2: These concepts ownership, resource, lifetime, careful memory handling. They echo
- 30:27Speaker 2: in many other languages and systems. It empowers you to
- 30:30Speaker 2: write code that's more robust, definitely more efficient, and ultimately safer.
- 30:34Speaker 1: Absolutely, it makes you think differently about how programs work.
- 30:38Speaker 1: So here's a final thought to leave you with. Considering
- 30:40Speaker 1: this constant evolution we've just discussed, especially in C plus
- 30:44Speaker 1: plus pilation, how might the whole concept of ownership in
- 30:47Speaker 1: programming languages keep changing in the coming years. What new
- 30:51Speaker 1: abstractions might we see built on top of these low
- 30:53Speaker 1: level memory foundations we've explored today,