Hacker News new | ask | show | jobs
by minamea 4838 days ago
Not being a picky prick this is a genuine question: What's the point of smart pointers? Seems to me that the #1 reason you would use a pointer is that you're allocating memory on the heap and you don't want the memory deallocated when the pointer goes out of scope.

Seems to me that the only difference between a smart pointer and declaring a variable is data on the heap vs data on the stack and there's not much difference there?

3 comments

Rust tasks cannot share anything. Smart pointers go on the 'exchange stack', which is technically shared by tasks, but since there's only one reference to anything in the stack, it's okay.

So you often create some sort of communications structure, keep one end yourself, and hand the other end off to a task. The smart-ness keeps this memory from being copied, which would be slow, but keeps you safe at the same time. Like this:

    use task::spawn;
    use pipes::stream;
    use pipes::Port;
    use pipes::Chan;

    fn main() {
      let (port, chan): (Port<int>, Chan<int>) = stream();

      do spawn |move chan| {
          chan.send(10);
      }

      io::println(int::str(port.recv()));
    }
More: http://www.rustforrubyists.com/book/chapter-07.html and http://www.rustforrubyists.com/book/chapter-08.html (I use the older-as-of-yesterday term 'owned pointer' rather than 'smart pointer.')
Simple. You use unique smart pointers if you do not know the size of your data at compile time.
A ~ pointer can still be returned from a function without being deallocated, and the contained data doesn't have to be copied (unlike data on the stack).
Reference please? I think this is wrong.
pcwalton is the voice of authority here, but to add to that, the following (verbose) example compiles and works as expected:

  fn make_string() -> ~str {
      return ~"foo";
  }

  fn main() {
     let string: ~str = make_string();

     io::println(string);
  } // deallocated here
My bad folks :)
It's true. Returning a `~` pointer transfers ownership (so your caller will be responsible for cleaning it up).
~ is similar to std::unique_ptr in C++. It is always owned in one place, but that ownership can be transferred at will.