mardi 29 octobre 2019

C++ primr 5 edition. unique_ptr constructor from custom deleter function

On C++ primer 5 edition. Chapter 12. Dynamic memory. The table that shows std::unique_ptr operations:

unique_ptr<T, D> u2 Null unique_ptrs that can point to objects of type T. u2 will use a callable object of type D in place of delete to free its pointer.

unique_ptr<T, D> u(d) Null unique_ptr that points to objects of type T that uses d, which must be an object of type D in place of delete.

But if I try to create one like this:

void cust_del(std::string* pStr){
     std::cout << *pStr + " destroying..." << std::endl;
     delete pStr;
}

int main(){


    {// new scope
    std::unique_ptr<std::string, void(*)(std::string*)> u(cust_del); // error

    std::unique_ptr<std::string, void(*)(std::string*)> u(new string("Hello unique!"), cust_del); // ok
    // or
    // std::unique_ptr<std::string, decltype(&cust_del)> u(new string("Hello unique!"), cust_del);

    }

}

So as I can see it is possible to construct a unique_ptr just from the custom delete function.

  • One last point: it is said there:

Unlike shared_ptr, there is no library function comparable to make_shared that returns a unique_ptr. Instead, when we define a unique_ptr, we bind it to a pointer returned by new. As with shared_ptrs, we must use the direct form of initialization:

But there is std::make_unique. Is this because make_uniqueis added by C++14 and the book has been rewritten for C++11?

Aucun commentaire:

Enregistrer un commentaire