On C++ primer 5 edition. Chapter 12. Dynamic memory. The table that shows std::unique_ptr operations:
unique_ptr<T, D>u2 Nullunique_ptrs that can point to objects of typeT.u2will use a callable object of typeDin place ofdeleteto free its pointer.
unique_ptr<T, D> u(d)Nullunique_ptrthat points to objects of typeTthat usesd, which must be an object of typeDin place ofdelete.
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