On C++ primer 5 edition. Chapter 12. Dynamic memory. The table that shows std::unique_ptr
operations:
unique_ptr<T, D>
u2 Nullunique_ptr
s that can point to objects of typeT
.u2
will use a callable object of typeD
in place ofdelete
to free its pointer.
unique_ptr<T, D> u(d)
Nullunique_ptr
that points to objects of typeT
that usesd
, which must be an object of typeD
in 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_unique
is added by C++14 and the book has been rewritten for C++11?
Aucun commentaire:
Enregistrer un commentaire