logoalt Hacker News

tgvyesterday at 10:28 AM1 replyview on HN

How does Rust (or C++) treat array indices as resources? And won't that defy the reason to use indices over pointers?


Replies

fookeryesterday at 5:44 PM

Here's how it works in some C++ libraries.

  struct resource {
    resource(ctx *c, ...) {index = c->store(...); ...;}
    size_t index;
    ctx *c;
    ~resource() {c->free(index);}
    // copy constructor+op creates new handle
    // move constructor+op copies the handle, maybe zeroes the current one 
  };
With this you can rely on RAII, smart pointers, upcoming lifetime checks and annotations, etc. The core idea is that you treat objects of classes like this as values and everything works out seamlessly. Even if they are 'pointers' in all but name. You can also overload the dereference operator for it to have pointer-like syntax, but that is discouraged.

When you have just once resource this might be overkill but for large projects with tangled webs of resources, this sort of setup really makes the code simpler and easier to design.

That's C++ for you, simple things look complex but once you get into big hairy projects things stay at the same level of complexity instead of becoming an unmanageable mess.

D almost supports RAII, and the compiler seems to do some automated copy to move conversion, but this is the sort of thing that really, really needs a large number of users and compiler implementers to iron out issues and corner cases. Nothing against D, the language is pretty neat!