Hacker News new | ask | show | jobs
by bunderbunder 2804 days ago
> This is a thing people say, but I think it's misleading. Reference counting can increase the lifetime of an object, but borrowing cannot. I've seen this really trip up beginners.

I'm not sure I follow.

The only reference-counted language I've used is (pre-ARC) Objective-C. There, it was a very common idiom to "borrow" objects - so common that it didn't even have a name. There was just objects you "retained" (that is, staked a claim on), and ones you didn't.

Maybe there's a pitfall to how the "automatic" part of automatic reference counting is typically implemented?

1 comments

It has been years since I've written objective-c, so I'll write out some psuedo-code. This may be wrong, please correct me! (It should map to C++ pretty directly, and certainly does in unsafe Rust.)

* You have an object. You call retain on it. You have a count of one.

* You also have a pointer to that object. The "borrow" in your analogy.

* You return this pointer, and stash it somewhere. The object still has a count of one, so it's still live, so this is okay.

* Later in your program, you use that pointer to call release.

Here, we've only ever had a reference count of one, but our object has lived across arbitrary inner scopes. In Rust, this would not work, unless you dropped into unsafe.

Obviously, with Arc and autoretain this kind of code doesn't get written anymore, I would hope. And even without, it wouldn't be guaranteed, so you'd want the "borrow" to actually bump the refcount. But Rust is about guaranteeing that it can't.

Ah, I think I follow.

So, it sounds to me like it's not necessarily that Rust's model is fundamentally different from "ref counting with a limit of 1", at least in terms of how you should be managing your memory, so much as that the language doesn't let you some things that you really shouldn't be doing in the first place.

Sometimes it felt like Objective C wouldn't just let you point a gun at your foot, it would actively cheer you on while you did it.