简体   繁体   中英

unique_ptr with reinterpret_cast, will the structure get freed correctly?

Will my dynamically allocated structure get freed properly by the unique_ptr?

unique_ptr<sockaddr> p;

switch (type) {
    case AF_INET:
        p.reset( reinterpret_cast<sockaddr *>(new sockaddr_in) );
        break;
    case AF_INET6:
        p.reset( reinterpret_cast<sockaddr *>(new sockaddr_in6) );
        break;
    case AF_UNIX:
        p.reset( reinterpret_cast<sockaddr *>(new sockaddr_un) );
        break;
    default:
        throw domain_error("Invalid domain");
}   

Do you have better alternatives? Is this a good coding style? Is it better to have 3 separate unique_ptr for each structure instead of only 1?

Unique ptr deletes its argument. Deleting things as the type they where not allocated as only avoids UB in narrow circumstances.

I'd be conservative and do this

template<class T, class U>
auto cleanup_as=[](U* u){ delete reinterpret_cast<T*>(u);};

template<class T>
using my_up=std:unique_ptr<T,void(*)(T*)>;

template<class T, class U>
my_up<T> wrap_up_as(U*pu){
  return my_up<T>(pu, cleanup_as<U,T>);
}

then your code becomes

my_up<sockaddr> p;

switch (type) {
  case AF_INET:
    p = wrap_up_as<sockaddr>( new sockaddr_in );
    break;

etc.

Here the extra function pointer destroyer in the unique ptr remembers how the structure was allocated, and at destruction cleans it up properly. Then some helper glue to make it easy to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM