netcan / asyncio

asyncio is a c++20 library to write concurrent code using the async/await syntax.
MIT License
812 stars 80 forks source link

Replace AddrInfoGuard with finally #14

Closed xiaozhuai closed 1 year ago

xiaozhuai commented 1 year ago
  1. AddrInfoGuard is bound to addrinfo, it's not reuseable.
  2. AddrInfoGuard did not impl the move constructor.
  3. AddrInfoGuard should mark copy constructor as delete.
  4. finally is simple, clean, safer, and higher reuseable.
  5. finally macro implement something like golang's defer keyword, but it will exec when leaving current scope, not function.
  6. Taken from https://gist.github.com/xiaozhuai/7b33e100f4f30918215e736a755d6df9
Be3y4uu-K0T commented 1 year ago

Why not just use a smart pointer (unique_ptr)?

std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> finally(server_info, &freeaddrinfo);
netcan commented 1 year ago

Why not just use a smart pointer (unique_ptr)?

std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> finally(server_info, &freeaddrinfo);

~the memory allocation is not neccessary.~ it's semantic doesn't make sense, sounds tricky.

xiaozhuai commented 1 year ago

Why not just use a smart pointer (unique_ptr)?

std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> finally(server_info, &freeaddrinfo);

Using a unique_ptr can't do this (multiple clean up)

finally {
    delete[] aaa;
    free(bbb);
    freeaddrinfo(info);
};

And in this case, unlock a mutex, If using a unique_ptr, it would be more complex and tricky.

finally {
    mutex.unlock();
};

And also, using lambda is better for compiler to do (inline) optimization.