|
|
|
|
|
by pjmlp
1830 days ago
|
|
Trying to be clever? Here is your Rust version, enjoy. use std::io::{self};
struct NetworkComponent {
socket : NetworkSocket
}
impl NetworkComponent {
fn new() -> NetworkComponent {
println!("Creating NetworkComponent");
NetworkComponent {
socket : NetworkSocket{}
}
}
fn do_sth_with_socket(&self) {
}
}
impl Drop for NetworkComponent {
fn drop(&mut self) {
println!("Dropping NetworkComponent");
}
}
struct NetworkSocket {
}
impl Drop for NetworkSocket {
fn drop(&mut self) {
println!("Dropping NetworkSocket");
}
}
fn main() -> io::Result<()> {
let mut foo = NetworkComponent::new();
{
let socket = NetworkSocket{};
foo.socket = socket;
}
foo.do_sth_with_socket(); // oops, runtime failure, socket closed
Ok(())
}
https://play.rust-lang.org/?version=stable&mode=debug&editio... |
|
The "oops" comment is invalid in your Rust example because the socket is still valid at that point.
Which is totally different than what would happen in C#, where you'd get use-after-free bug (actually use-after-close).
Try with resources is not RAII. It is a lot weaker.