我刚刚发现了`std::shared_ptr`的“别名构造函数”,于是我开始问自己,“为什么`std::unique_ptr`没有相应的构造函数呢?”
也就是说,如果你想要分配一个`Foo`,以便将其`Bar`成员传递给完全管理`Foo`生存期的函数,那么能够这样做不是很好吗?
这适用于std::shared_ptr(http://ideone.com/pDK1bc)。
也就是说,如果你想要分配一个`Foo`,以便将其`Bar`成员传递给完全管理`Foo`生存期的函数,那么能够这样做不是很好吗?
#include <memory>
struct B {}
struct A {
B b;
}
void f(std::unique_ptr<B> b);
std::unique_ptr<A> a = std::make_unique<A>();
std::unique_ptr<B> b { std::move(a), &(a->b) }; // a now invalid.
f(std::move(b)); // f now responsible for deleting the A.
这适用于std::shared_ptr(http://ideone.com/pDK1bc)。
#include <iostream>
#include <memory>
#include <string>
struct B {
std::string s;
};
struct A {
B b;
A(std::string s) : b{s} {};
~A() { std::cout << "A deleted." << std::endl; }
};
void f(std::shared_ptr<B> b) {
std::cout << "in f, b->s = " << b->s << " (use_count=" << b.use_count() << ")" << std::endl;
}
int main() {
std::shared_ptr<A> a = std::make_shared<A>("hello");
std::shared_ptr<B> b { a, &(a->b) };
a.reset(); // a now invalid.
std::cout << "before f, b->s = " << b->s << " (use_count=" << b.use_count() << ")" << std::endl;
f(std::move(b)); // f now responsible for deleting the A.
std::cout << "after f" << std::endl;
return 0;
}
输出预期结果
before f, b->s = hello (use_count=1)
in f, b->s = hello (use_count=1)
A deleted.
after f
为什么没有包含这样的东西有合理的逻辑原因吗?或者,使用一个自定义删除器删除A
的unique_ptr<B>
来模拟它是一个不好的想法吗?
unique_ptr<T>
不兼容,除非您对删除器进行类型擦除,这会增加更多的开销。 - T.C.unique_ptr<T, default_deleter<T>>
很好地交互。至少,在一个方向上可以进行转换。 - Ben Voigt