mercredi 12 mai 2021

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 ?

Aucun commentaire:

Enregistrer un commentaire