从同一个指针构造两个shared_ptr对象
我有一个来自“C++ 标准库扩展”的问题:
练习 6
我在2.4.2节中说过 你不应该构建两个 来自同一对象的shared_ptr对象 指针。 危险在于,两者 Shared_ptr 对象或其后代 最终会尝试删除 资源,这通常会导致 麻烦。 事实上,如果 你很小心。 并不是特别 有用,但是编写一个程序 构建两个 来自的shared_ptr对象 相同的指针并删除 资源仅一次。
以下是我的答案:
template <typename T>
void nonsence(T*){}
struct SX {
int data;
SX(int i = 0) :
data(i) {
cout << "SX" << endl;
}
~SX() {
cout << "~SX" << endl;
}
};
int main(int argc, char **argv) {
SX* psx=new SX;
shared_ptr<SX> sp1(psx),sp2(psx,nonsence<SX>);
cout<<sp1.use_count()<<endl;
return 0;
}
但我认为这不是一个好的解决方案——因为我不想通过使用构造函数来解决它。 谁能给我一个更好的吗? 谢谢,请原谅我糟糕的英语。
I have a problem from "The C++ Standard Library Extensions":
Exercise 6
I said in Section 2.4.2
that you shouldn't construct two
shared_ptr objects from the same
pointer. The danger is that both
shared_ptr objects or their progeny
will eventually try to delete the
resource, and that usually leads to
trouble. In fact, you can do this if
you're careful. It's not particularly
useful, but write a program that
constructs two
shared_ptr objects from
the same pointer and deletes the
resource only once.
below is my answer:
template <typename T>
void nonsence(T*){}
struct SX {
int data;
SX(int i = 0) :
data(i) {
cout << "SX" << endl;
}
~SX() {
cout << "~SX" << endl;
}
};
int main(int argc, char **argv) {
SX* psx=new SX;
shared_ptr<SX> sp1(psx),sp2(psx,nonsence<SX>);
cout<<sp1.use_count()<<endl;
return 0;
}
but I don't think it is a good solution--because i don't want solving it by use constructor. can anyone give me a better one?
thx, forgive my bad english.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你发现的技巧虽然无用,但却有效。
shared_ptr
的核心功能是引用计数,您在这里颠覆了它。 删除器(第二个构造函数参数)用于将shared_ptr
与普通指针以外的资源一起使用。 您可以将它与文件一起使用,例如:与数据库连接、套接字等相同,以及 RAII 一般而言。
The trick you found is valid, though useless. The central feature of
shared_ptr
is reference-counting, which you subvert here. The deleter (the second constructor argument) is there for usingshared_ptr
with resources other then plain pointers. You could use it with files, e.g:Same with database connections, sockets, etc. etc. and RAII in general.
你可以用shared_from_this看看boost是如何解决这个问题的。 这是代码。
You can look at how boost solves it with shared_from_this. Here's the code.
我从 boost doc 得到了“标准”答案:
http:// www.boost.org/doc/libs/1%5F38%5F0/libs/smart%5Fptr/sp%5Ftechniques.html#another_sp
I got the "STANDARD" answer from boost doc :
http://www.boost.org/doc/libs/1%5F38%5F0/libs/smart%5Fptr/sp%5Ftechniques.html#another_sp
您所需要做的就是从第一个
shared_ptr
构造第二个shared_ptr
。只有当指向它的所有共享指针都被销毁时,创建的 SX 才会被正确删除。
All you need to do is construct the second
shared_ptr
from the firstshared_ptr
.The created SX will then properly be deleted only when all shared pointers to it are destroyed.