我刚刚发现std::shared_ptr
的‘走样构造’,找到自己问“为什么不标准::的unique_ptr有相应的一个?为什么不std :: unique_ptr具有像std :: shared_ptr一样的别名构造函数?
,如果你想分配一个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
有为什么不包含这样的事情一个合乎逻辑的理由?和/或,用unique_ptr<B>
与定制的删除程序来删除A
来模拟它是不是一个好主意?
然后,由于删除者的类型部分,除非您键入删除删除者,否则它不会与纯粹的'unique_ptr'很好地互操作,这更加额外的开销。 –
@ T.C .:即使您键入删除删除程序,它也不会与'unique_ptr>'互操作。至少,只能在一个方向上进行转换。 –
@理论上讲,只要失败是允许的。 – Yakk