3 ms·
>" Coming from a C++/Objc/Go background I was used to creating an object on the heap and holding a reference counted/garbage collected pointer to the object whe
by bogomipz 10y ago
>" Coming from a C++/Objc/Go background I was used to creating an object on the heap and holding a reference counted/garbage collected pointer to the object wherever it was used. This is shared ownership of state, a style of coding Rust considers to be so egregious that it is a compile error."
Is the idea that because anyone else can come along and make reference to the same object on the heap mean "shared" in this context? If so would the opposite of "shared" be "owned" or "owned exclusively"? Is this what borrow checker is "checking" then?
- lobster_johnson 10y agoIn C++ the closest equivalent is probably unique_ptr [1], which only lets one reference exist at any given time and destroys the pointer when it goes out of scope, but also allows transferring the ownership to someone else. The C++ equivalent of Rust's Rc (reference counted pointer) is std::shared_ptr. [1] http://en.cppreference.com/w/cpp/memory/unique_ptr http://en.cppreference.com/w/cpp/memory/unique_ptr
- bogomipz 10y agoThanks for the responses, these are really helpful.
- db48x 10y agoExactly. You can have as many immutable references to an object as you want, or you can have one mutable reference to it, not both. (Each of those references is how you borrow something from the real owner, hence the name.) The borrow checker is that part of the compiler that makes sure that these borrowing rules are followed. Other rules are implemented by other parts of the compiler; the type system has the job of making sure you don't try to write to something that you only have an immutable reference to, for example.