4 ms·
Let's translate this code to C++: class X { public: Y* getY(void) { return &y; } private: Y y; }; }
by m1el 10y ago
Let's translate this code to C++:
class X {
public:
Y* getY(void) {
return &y;
}
private:
Y y;
};
}
`getY` returns a pointer to the struct field, this field is allocated as a part of the struct. There is no way (in C++) to verify that this pointer does not outlive the struct itself. In other words, your pointer may become stale, and the compiler has no way to check for it.
Rust has a resource ownership model (borrow checker) that allows it to check at compile time that references do not outlive the data.
- akie 10y agoAh, I see! Thank you.
- humanrebar 10y agoA little closer would be to use a shared_ptr<X> and shared_ptr<Y> that share the same reference count (1). It's not exactly the same thing, though, since Rust gives you some safe usage checks that you don't get with shared_ptr. That is, vanilla Rust objects have lifetime semantics closer to unique_ptr than shared_ptr. (1): See constructor number 7 here, which was designed for this purpose: http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_pt...
- dbaupp 10y agoIt also isn't the same in that it comes with the cost of allocation and reference counting.
- nallerooth 10y agoThanks!
- blub 10y agoBoth the original example and your translation exhibit poor API design: it's an antipattern to return mutable references to member variables. This would remove all encapsulation, which is probably the most important principle of OOP. Nevertheless, a better solution was pointed out in an answer on the blog and by humanrebar.
- erikdesjardins 10y agoThe original example does not return a mutable reference; in Rust you must explicitly opt in to mutability. Compare [1] and [2]. [1]: https://play.rust-lang.org/?gist=78e7af18c6fc7d37d9df96be63ac23d8 https://play.rust-lang.org/?gist=78e7af18c6fc7d37d9df96be63a... [2]: https://play.rust-lang.org/?gist=2072a18b674685f20c9d1504a8829a3d https://play.rust-lang.org/?gist=2072a18b674685f20c9d1504a88...
- blub 10y agoOh ok, my bad. Then the C++ translation above should probably be a const& in C++, which is acceptable. The returned reference could in that case be stored, but it's risky and a bad practice.