lab132 / krepel

2 stars 0 forks source link

Ownership #20

Closed Manuzor closed 8 years ago

Manuzor commented 8 years ago

Regular reference counting has some problems:

Inspired by Rust, I have come up with an ownership system that does reference counting only on special borrowed objects, that wrap the original object. I guess you could say it is a combination of std::unique_ptr and std::shared_ptr.

An example should make things more clear:

class Foo { int data; };
void cleanUpFoo(Foo* pFoo) { delete pFoo; }
void doStuff(kr::Borrowed<Foo> foo) { printf("foo: %d\n", foo->data); }

// ...
auto fooptr = new Foo{ 42 };

// Create an owner for fooptr.
// Ref count will be 0 at this point
kr::Owned<Foo> foo = own(foo, cleanUpFoo);

// Ref count within doStuff is 1, prints "foo: 42",
// and resets the ref count to 0 on return.
doStuff(borrow(foo));

// Invokes cleanUpFoo and resets its internal state.
// If anything was still borrowed at this point,
// an assertion would have triggered.
foo.reset();

Advantages:

On top of this, something like a make function would be possible, which takes care of specifying the deleter for you:

template<typename T, typename Args...>
kr::Owned<T> make(Args...) { /* Use the default allocator, forward args, etc... */ }
kr::Owned<T> makeWith(Allocator* allocator, Args...) { /* Use the default allocator, forward args, etc... */ }
auto foo1 = make<Foo>(42);
auto foo2 = makeWith<Foo>(myFancyAllocator, 42);

TODO

Things that are still left to do at this point:

Manuzor commented 8 years ago

Things done from the TODO list:

This means it would be ready to be merged back. Any volunteers for reviewing?

Manuzor commented 8 years ago

I know there are a lot of changes. If one of you is willing, we could go over the crucial parts together. Not every little change has to be reviewed, of course.

If none of you would like to review this, then I will just merge it back.