初级 5 版。 unique_ptr 自定义删除函数的构造函数
primr 5 edition. unique_ptr constructor from custom deleter function
C++ primer 5 版。第 12 章动态内存。显示std::unique_ptr
操作的table:
unique_ptr<T, D>
u2 Null unique_ptr
s 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
.
但是如果我尝试创建一个这样的:
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);
}
}
因此,正如我所见,仅从自定义删除函数构建 unique_ptr
是不可能的。
- 最后一点:据说那里:
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:
但是有std::make_unique
。这是因为 make_unique
是 C++14 添加的并且本书已针对 C++11 重写了吗?
std::unique_ptr
没有只接受自定义删除器的构造函数。如果你想要一个带有自定义删除器的空指针,你必须将 nullptr
作为指针值传递。
你的第二点是正确的。他们直到 c++14 才添加 make_unique,除了 C++11 是一个巨大的修订并且一些功能没有加入之外,没有其他原因。
C++ primer 5 版。第 12 章动态内存。显示std::unique_ptr
操作的table:
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
.
但是如果我尝试创建一个这样的:
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);
}
}
因此,正如我所见,仅从自定义删除函数构建 unique_ptr
是不可能的。
- 最后一点:据说那里:
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:
但是有std::make_unique
。这是因为 make_unique
是 C++14 添加的并且本书已针对 C++11 重写了吗?
std::unique_ptr
没有只接受自定义删除器的构造函数。如果你想要一个带有自定义删除器的空指针,你必须将 nullptr
作为指针值传递。
你的第二点是正确的。他们直到 c++14 才添加 make_unique,除了 C++11 是一个巨大的修订并且一些功能没有加入之外,没有其他原因。