boost::shared_ptr 语义(复制)
我只是想用新的眼光来看看下面的代码是正确的:
对象 trifoo 中包含的指针(存储在 ptr_vector 中)是共享指针 f、g、h。
另外,trifoo的构造函数中的shared_ptr复制的结果是什么;这是“共享”shared_ptr 的正确方法吗?确保引用计数增加等。我能够测试验证所有其他疑问,但我不确定如何(正确)检查这一点。也欢迎任何批评。
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
class foo {
int a, b;
public:
foo(int A, int B) : a(A), b(B) {}
};
typedef boost::shared_ptr<foo> foo_ptr;
class trifoo {
foo_ptr c, d, e;
public:
trifoo(const foo_ptr& C, const foo_ptr& D, const foo_ptr& E) : c(C), d(D), e(E) {}
};
int main() {
for (int i = 0; i < 5000000; i++) {
foo_ptr f(new foo(1,2));
foo_ptr g(new foo(2,3));
foo_ptr h(new foo(4,5));
boost::ptr_vector<trifoo> tris;
tris.push_back(new trifoo(f, g, h));
}
return 0;
}
注意:无意义的循环是为了测试内存泄漏,但没有发生。
I just wanted to have a fresh pair of eyes that the below code is correct in that:
The pointers contained in the object trifoo (stored in a ptr_vector) are the shared pointers f, g, h.
Also, what is the result of the shared_ptr copy in the constructor of trifoo; is this the correct method of 'sharing' shared_ptr, ensuring reference counts are increased etc. All my other doubts I was able to test to verify, but I'm not sure how I can check this (properly). Any critique is welcome also.
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/shared_ptr.hpp>
class foo {
int a, b;
public:
foo(int A, int B) : a(A), b(B) {}
};
typedef boost::shared_ptr<foo> foo_ptr;
class trifoo {
foo_ptr c, d, e;
public:
trifoo(const foo_ptr& C, const foo_ptr& D, const foo_ptr& E) : c(C), d(D), e(E) {}
};
int main() {
for (int i = 0; i < 5000000; i++) {
foo_ptr f(new foo(1,2));
foo_ptr g(new foo(2,3));
foo_ptr h(new foo(4,5));
boost::ptr_vector<trifoo> tris;
tris.push_back(new trifoo(f, g, h));
}
return 0;
}
Note: the pointless loop was to test memory leaks, of which none occurred.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该代码在技术上似乎是正确的。
复制
shared_ptr
的语义,无论是如何完成的,都是增加了所引用对象的引用计数。它就是有效的。没什么好担心的。不过,有些样式问题:
通过引用传递
shared_ptr
或声明它const
是没有意义的。那是因为它总是可以被复制。只需按值传递这些shared_ptr
。在实际可能的情况下,使用构造函数初始值设定项列表而不是赋值。
将三个
new
放在不同的表达式中是非常好的。它避免了异常安全陷阱。但更好的是,将该创建逻辑放入工厂函数中。干杯&呵呵,
The code seems to be technically correct.
Semantics of copying a
shared_ptr
, however it is done, is that the reference count of the referred-to object is increased. It just works. Nothing to worry about.Some style issues, though:
Passing
shared_ptr
by reference, or declaring itconst
, is meaningless. That's because it can always be copied. Just pass thoseshared_ptr
's by value.Use constructor initializer lists instead of assignments where practically possible.
Having the three
new
's in different expressions is very good. It avoids an exception safety pitfall. But even better, put that creation logic in a factory function.Cheers & hth.,