【发布时间】:2016-01-08 03:11:36
【问题描述】:
我刚刚发现std::shared_ptr 的“别名构造函数”,发现自己在问“为什么 std::unique_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 的自定义删除器来模拟它是不是一个坏主意?
【问题讨论】: