frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

fp.

Open in hackernews

Understanding C++ Ownership System

https://blog.aiono.dev/posts/understanding-c++-ownership-system.html
35•todsacerdoti•2h ago

Comments

Dwedit•1h ago
C++: Where you can accidentally deallocate an object that's still in the call stack. (true story)
einpoklum•1h ago
Well, you can also write:

   int x = 123;
   delete &x;
and that would compile. But it's not a very good idea and you should be able to, well, not do that.

In modern C++, we avoid allocating and deallocating ourselves, as much as possible. But of course, if you jump to arbitrary code, or overwrite something that's due as input for deallocation with the wrong address, or similar shenanigans, then - it could happen.

kccqzy•1h ago
You can also do that intentionally and correctly. After all `delete this;` is a valid statement that can occasionally be useful. That said, I’ve only seen this in old pre-C++11 code that does not adhere to the RAII best practice.
HarHarVeryFunny•1h ago
The trouble with C++ is that it maintains backwards compatibility with C, so every error-prone thing you could do in C, you can still do in C++, even though C++ may have a better way.

The modern, safest, way to use C++, is to use smart pointers rather than raw pointers, which guarantee that nothing gets deleted until there are no more references to it, and that at that point it will get deleted.

Of course raw pointers and new/delete, even malloc/free, all have their uses, and without these low level facilities you wouldn't be able to create better alternatives like smart pointers, but use these at your own peril, and don't blame the language if you mess up, when you could have just done it the safe way!

aw1621107•34m ago
> which guarantee that nothing gets deleted until there are no more references to it, and that at that point it will get deleted.

To be more precise, C++'s smart pointers will ensure something is live while specific kinds of references the smart pointer knows about are around, but they won't (and can't) catch all references. For example, std::unique_ptr ensures that no other std::unique_ptr will own its object and std::shared_ptr will not delete its object while there are other std::shared_ptrs around that point to the same object, but neither can track things like `std::span`/`std::string_view`/other kinds of references into their object.

jesse__•1h ago
Does anyone reading this have links to people who have written specifically about a C++ ownership model that rejects the smart_ptr/RAII/friends model in favor of an ownership model that embraces bulk allocations, arenas, freelists, etc? I know there are groups of highly productive programmers that feel the traditional C++ ownership model is hot garbage, and I'd love a resource that puts down specific arguments against it, but I've never come across one myself.

Edit: clarity

rubymamis•1h ago
I'm interested in the same! There are plenty of resources for C[1][2]. I just looked into my old notes and found a post for C++[3].

[1] https://btmc.substack.com/p/memory-unsafety-is-an-attitude-p...

[2] https://www.gingerbill.org/series/memory-allocation-strategi...

[3] https://dmitrysoshnikov.com/compilers/writing-a-pool-allocat...

jesse__•1h ago
Nice, thanks. I haven't read those gingerbill ones, I'll take a look :D
otherjason•1h ago
What makes you think that RAII- and arena-based strategies are in tension with one another? RAII and smart pointers are more related to the ownership and resource management model. Allocating items in bulk or from arenas is more about where the underlying resources and/or memory come from. These concepts can certainly be used in tandem. What is the substance of the argument that RAII, etc. are "hot garbage?"
einpoklum•1h ago
In my library [1], wrapping the CUDA APIs in modern C++, I do allocations which are not exactly from an arena, but something in that neighborhood - memory spaces on context on GPU devices.

Unlike the GP suggests, and like you suggest, I have indeed embraced RAII in the library - generally, not just w.r.t. memory allocation. I have not, however, replicated that idioms of the standard library. So, for example:

* My allocations are never typed.

* The allocation 'primitives' return a memory_region type - essentially a pointer and a size; I discourage the user from manipulating raw pointers.

* Instead of unique_ptr's, I encourage the use of unique_span's: owning, typed, lightweight-ish containers - like a fusion of std::span<T> and std::unique_ptr<T[]> .

I wonder if that might seem less annoying to GP.

---

[1] : https://github.com/eyalroz/cuda-api-wrappers/

jesse__•1h ago
In reverse order they were asked ..

The best argument I've ever come across against using RAII is that you end up with these nests of objects pointing to one another, and if something fails, the cleanup code can really only do one thing, which is unwind and deallocate (or whatever the cleanup path is). This structure, generally, precludes the possibility of context dependent resource re-usage on initialization failure, or on deallocation, because you kind of have to have only one deallocation path. Obviously, you could imagine supporting in an RAII context, but, the point is that you probably have to put a fair bit of conscious effort into doing that, whereas if you have a less .. rigid.. ownership model, it becomes completely trivial.

I agree that the allocation model and ownership model are independent concepts. I mentioned arena allocation because the people I know that reject the traditional C++ ownership model generally tend to favor arenas, scratch space, freelists, etc. I'm specifically interested in an ownership model that works with arenas, and tracks ownership of the group of allocations, as opposed to the typical case we think about with RAII where we track ownership of individual allocations.

aw1621107•1h ago
> explicitly rejects the smart_ptr/RAII/friends model in favor of bulk allocations, arenas, freelists, etc?

These aren't mutually exclusive; you can use the former to manage the latter, after all.

> I know there are groups of highly productive programmers that feel the traditional C++ ownership model is hot garbage

I'm not aware of links off the top of my head, but I can try to summarize the argument.

From my understanding, the argument against RAII/etc. has more to do with the mindset it supposedly encourages more than the concept itself - that RAII and friends makes it easy to think more in terms of individual objects/elements/etc. instead of batches/groups, and as a result programmers tend to follow the easy path which results in less performant/more complex code. By not providing such a feature, so the argument goes, programmers no longer have access to a feature which makes less-efficient programming patterns easy and so batched/grouped management of resources becomes more visible as an alternative.

jesse__•1h ago
Agreed. I guess I'm interested in anyone that's specifically written about ownership strategies that lean into the group allocation thing.
nwlieb•1h ago
Yes: https://m.youtube.com/watch?v=xt1KNDmOYqA

Title: “ Casey Muratori | Smart-Pointers, RAII, ZII? Becoming an N+2 programmer”

jesse__•1h ago
Good one. I was blessed to have the opportunity to watch that one live, on stream. It's always stuck with me and, now that I think about it, is the best resource I know of that puts those ideas into words/writing.
verall•1h ago
If you have requirements for high performance then the traditional C++ "ownership model" (I would say a better description is "ownership strategy") is definitely "slow". It's pretty "safe" in that you usually aren't going to leak a bunch with it but bull allocations, arenas, and freelists are all potentially faster. And you wouldn't use them if they were slower since they're (usually) more to deal with.

But even in software using these strategies, they probably will be using different ownership strategies in different parts of the code. Once you're writing high performance code, you will use specific strategies that give you the best results. But it's completey domain specific.

GrowingSideways•1h ago
Such a model likely would not be referred to as "ownership". This is a relatively recent metaphor for memory management that came well after the concepts you mentioned. The fact that such a metaphor is core to rust's memory model is no coincidence.
HarHarVeryFunny•22m ago
Those types of allocation technique were common back in the day for efficiency reasons, maybe still relevant for things like embedded programming where you need to be more careful about memory usage and timing, but I would say that nowadays for normal application usage you are better off using smart pointers.

It's not a matter of one being strictly better than the other, but rather about using the right tool for the job.

jesse__•6m ago
Many soft-realtime systems make use of these techniques, specifically 3D graphics and game engines.
einpoklum•1h ago
The title reminds of this:

https://youtu.be/TGfQu0bQTKc?si=7TiDRic6LaWI1Xpc&t=70

"In Rust you need to worry about borrowing. In C++ you don't have to worry about borrowing; in C++ you have to worry about ownership, which is an old concept..." :-P

jurschreuder•1h ago
I don't know why people use 'new' and 'delete' in all the examples how memory in C++ works because you never normally use them during coding only if you want to make your own container which you might do once to learn about the internals.

C++ by default creates objects by value (opposed to any other language) and when the variable goes out of scope the variable is cleaned up.

'new' you use when you want to make a global raw pointer outside of the normal memory system is how I would see it. You really never use it normally at least I don't.

A good rule of thumb is not to use 'new'.

vlovich123•55m ago
And yet, I interviewed 10 people easily where I was using new and delete in the example code and only one person asked "hey - can we use unique_ptr?".
oxag3n•40m ago
Ownership problems with pointer/references don't end with allocation.

A codebase can use only std::make_unique() to allocate heap, and still pass around raw pointers to that memory (std::unique_ptr::get()).

The real problem is data model relying on manual lifetime synchronization, e.g. pass raw pointer to my unique_ptr to another thread, because this thread joins that thread before existing and killing the unique_ptr.

mackeye•20m ago
many schools (like mine) don't teach unique pointers in the pure "programming" class sequence, but offer a primer in advanced classes where c++ happens to be used, with the intent to teach manual memory management for a clearer transition to e.g. upper-levels which use c.
johannes1234321•13m ago
Well in interviews this is tricky. Sometimes the interviewer wants to see I can new/delete properly, sometimes this tells me "well, if that's the style they are using I better go elsewhere"

If it's done as part of a "here is legacy code, suggest ways to improve it" question one should point it out, though.

mikepurvis•45m ago
Yup, just emplace the object directly into the container, or at worst create it by value and then add it to the container with std::move.
unclad5968•23m ago
It just makes for an easily understandable example. I don't think the post is advocating for the use of new/delete over smart pointers.
duped•16m ago
People use `new` and `delete` when explaining memory in C++ because those are the language primitives for allocating and releasing memory in C++.

That rule of thumb is only a useful rule if you don't care about how memory works and are comfortable with abstractions like RAII. That's fine for lots of real code but dismissing `new` and `delete` on principle is not interesting or productive for any discussion.

dpsych•25m ago
I think in the `Move` section the delete[] should be delete[] old_buffer; rather than new_buffer;
cocoto•22m ago
Why are some examples full of errors? The `set_vec` method for instance does not bind the reference, you can't change the reference itself... so the code would simply copy the vector and there would be no dangling reference... And `B` is missing a constructor since the default constructor would be ill-formed (you can't default initialize a reference).

Anyway the article is quite approachable, do not take my criticism to shy away from writing!

vqsubu16•12m ago
Why there is the calling of "read(buffer.get());" in the first example (inside of the 'while' loop)?

It is a 'char *buffer' type, unless I'm mistaken raw pointers don't have methods/member functions?

dundarious•10m ago
copy-paste error given the next example uses a smart ptr type that has a .get() to get the actual pointer.

What came first: the CNAME or the A record?

https://blog.cloudflare.com/cname-a-record-order-dns-standards/
220•linolevan•5h ago•80 comments

Nearly a third of social media research has undisclosed ties to industry

https://www.science.org/content/article/nearly-third-social-media-research-has-undisclosed-ties-i...
101•bikenaga•4h ago•48 comments

Study: Minimal evidence links social media, gaming to teen mental health issues

https://www.manchester.ac.uk/about/news/time-spent-on-gaming-and-social-media/
29•giuliomagnifico•5d ago•30 comments

Understanding C++ Ownership System

https://blog.aiono.dev/posts/understanding-c++-ownership-system.html
35•todsacerdoti•2h ago•32 comments

The coming industrialisation of exploit generation with LLMs

https://sean.heelan.io/2026/01/18/on-the-coming-industrialisation-of-exploit-generation-with-llms/
25•long•14h ago•11 comments

Level S4 solar radiation event

https://www.swpc.noaa.gov/news/g4-severe-geomagnetic-storm-levels-reached-19-jan-2026
34•WorldPeas•2h ago•6 comments

Graphics In Flatland – 2D ray tracing [video]

https://www.youtube.com/watch?v=WYTOykSqf2Y
34•evakhoury•3d ago•9 comments

Targeted Bets: An alternative approach to the job hunt

https://www.seanmuirhead.com/blog/targeted-bets
10•seany62•1h ago•6 comments

Simple Sabotage Field Manual (1944) [pdf]

https://www.cia.gov/static/5c875f3ec660e092cf893f60b4a288df/SimpleSabotage.pdf
65•praptak•2h ago•34 comments

Nanolang: A tiny experimental language designed to be targeted by coding LLMs

https://github.com/jordanhubbard/nanolang
8•Scramblejams•1h ago•0 comments

Show HN: Subth.ink – write something and see how many others wrote the same

https://subth.ink/
46•sonnig•4h ago•31 comments

Show HN: An interactive physics simulator with 1000's of balls, in your terminal

https://github.com/minimaxir/ballin
11•minimaxir•5h ago•2 comments

From Nevada to Kansas by Glider

https://www.weglide.org/flight/978820
62•sammelaugust•3d ago•8 comments

Notes on Apple's Nano Texture (2025)

https://jon.bo/posts/nano-texture/
101•dsr12•4h ago•63 comments

Conditions in the Intel 8087 floating-point chip's microcode

https://www.righto.com/2025/12/8087-microcode-conditions.html
65•diogotozzi•4d ago•14 comments

The assistant axis: situating and stabilizing the character of LLMs

https://www.anthropic.com/research/assistant-axis
11•mfiguiere•1h ago•0 comments

Weight Transfer for RL Post-Training in under 2 seconds

https://research.perplexity.ai/articles/weight-transfer-for-rl-post-training-in-under-2-seconds
7•jxmorris12•2h ago•0 comments

Use Social Media Mindfully

https://danielleheberling.xyz/blog/mindful-social-media/
5•mooreds•1h ago•0 comments

Show HN: A creative coding library for making art with desktop windows

https://github.com/willmeyers/window-art
18•willmeyers•2h ago•2 comments

Sending Data over Offline Finding Networks

https://cc-sw.com/find-my-and-find-hub-network-research/
48•findmysanity•5d ago•3 comments

CSS Web Components for marketing sites (2024)

https://hawkticehurst.com/2024/11/css-web-components-for-marketing-sites/
91•zigzag312•7h ago•41 comments

Show HN: Pipenet – A Modern Alternative to Localtunnel

https://pipenet.dev/
74•punkpeye•6h ago•13 comments

Bypassing Gemma and Qwen safety with raw strings

https://teendifferent.substack.com/p/apply_chat_template-is-the-safety
85•teendifferent•17h ago•23 comments

There's a hidden Android setting that spots fake cell towers

https://www.howtogeek.com/theres-a-hidden-android-setting-that-spots-fake-cell-towers/
63•rmason•2h ago•16 comments

Letter from a Birmingham Jail (1963)

https://www.africa.upenn.edu/Articles_Gen/Letter_Birmingham.html
368•hn_acker•3h ago•121 comments

A decentralized peer-to-peer messaging application that operates over Bluetooth

https://bitchat.free/
550•no_creativity_•15h ago•305 comments

Fix your robots.txt or your site disappears from Google

https://www.alanwsmith.com/en/37/wa/jz/s1/
97•bobbiechen•5h ago•60 comments

San Francisco coyote swims to Alcatraz

https://www.sfgate.com/local/article/san-francisco-coyote-alcatraz-21302218.php
118•kaycebasques•20h ago•22 comments

A Brief History of Ralph

https://www.humanlayer.dev/blog/brief-history-of-ralph
48•dhorthy•4h ago•26 comments

GLM-4.7-Flash

https://huggingface.co/zai-org/GLM-4.7-Flash
307•scrlk•7h ago•103 comments