Boost智能指针:我可以用更简洁的方式表达它吗?
今天我一直在使用 Boost::shared_ptr,我有一个问题。
vector<shared_ptr<KlasaA> > vec;
vec.push_back(shared_ptr<KlasaA>(new KlasaB));
vec.push_back(shared_ptr<KlasaA>(new KlasaC));
vec.push_back(shared_ptr<KlasaA>(new KlasaC));
vec.push_back(shared_ptr<KlasaA>(new KlasaA));
for (vector<shared_ptr<KlasaA> >::const_iterator c_it = vec.begin();
c_it != vec.end(); ++c_it)
{
cout << c_it->get()->foo(10) << endl;
}
上面的循环遍历一个向量并多态调用 foo(10)
。
我的问题是:
可以
for (vector<shared_ptr<KlasaA> >::const_iterator c_it = vec.begin();
c_it != vec.end(); ++c_it)
吗
cout << c_it->get()->foo(10) << endl;
用更简洁的方式表达 ?提前致谢。
today I've been working with Boost::shared_ptr, and I have a question.
vector<shared_ptr<KlasaA> > vec;
vec.push_back(shared_ptr<KlasaA>(new KlasaB));
vec.push_back(shared_ptr<KlasaA>(new KlasaC));
vec.push_back(shared_ptr<KlasaA>(new KlasaC));
vec.push_back(shared_ptr<KlasaA>(new KlasaA));
for (vector<shared_ptr<KlasaA> >::const_iterator c_it = vec.begin();
c_it != vec.end(); ++c_it)
{
cout << c_it->get()->foo(10) << endl;
}
The loop above goes through a vector and polymorphically invokes foo(10)
.
My question is:
Can...
for (vector<shared_ptr<KlasaA> >::const_iterator c_it = vec.begin();
c_it != vec.end(); ++c_it)
and
cout << c_it->get()->foo(10) << endl;
be expressed in a more concise way? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
Boost.Foreach
图书馆。然后它会看起来非常简洁明了:You could use
Boost.Foreach
library. Then it will look pretty concise and clear:据我所知,您的迭代器初始化似乎尽可能紧凑。如果你真的愿意,你可以将循环函数写成:
这样只节省了 4 个字符,但看起来确实更清晰一些。
Your iterator initialization seems about as compact as can be, as far as I can see. If you really want to, you could write the loop function as:
This saves only 4 characters, but it does look a bit clearer.
shared_ptr
有一个隐式的向下转型构造函数,因此您可以编写注意
shared_ptr
类型为shared_ptr
并且 vec 需要shared_ptr;
。考虑到这一点,您可以用
make_shared
函数调用替换shared_ptr
构造函数(无论如何,这实际上可能是首选)。这将为您省去输入一堆类名的麻烦。
make_shared
接受将转发的参数,因此make_shared
是new X
的一个很好的替代品。您可能会注意到这里存在潜在的性能影响:
make_shared
数据结构可以(将会?)不同,并且存在额外的隐式转换,但这可能会被编译器优化掉。配置文件并检查。shared_ptr
has an implicit downcast constructor, so you can writeNotice the
shared_ptr
type isshared_ptr<KlasaB>
and vec expectsshared_ptr<KlasaA>
.With this in mind, you can replace
shared_ptr
constructor withmake_shared
function call (which may actually be preferred, anyway).This will save you the hassle of typing in a bunch of class names.
make_shared
accepts arguments which it will forward, somake_shared<X>
is a nice replacement fornew X
.You may notice that there are potential performance implications here: the
make_shared
data structure can (will?) be different, and there is an extra implicit conversion, but that may be optimized away by the compiler. Profile and check.根据编译器的不同,您可以执行以下操作:
Dependently on compiler you may do such things: