BOOST_FOREACH 迭代 boost::shared_ptr;
我正在做与此项目类似的事情 正确的 BOOST_FOREACH 用法?
但是,我返回的列表已包装在 boost::shared_ptr 中。如果我没有在 BOOST_FOREACH 循环之前将列表分配给变量,我会在运行时崩溃,因为列表会被破坏,因为它是临时的。
boost::shared_ptr< list<int> > GetList()
{
boost::shared_ptr< list<int> > myList( new list<int>() );
myList->push_back( 3 );
myList->push_back( 4 );
return myList;
}
然后......
// Works if I comment out the next line and iterate over myList instead
// boost::shared_ptr< list<int> > myList = GetList();
BOOST_FOREACH( int i, *GetList() ) // Otherwise crashes here
{
cout << i << endl;
}
我希望能够使用上面的内容而不必引入变量“myList”。 这可能吗?
I'm doing something similar to this item Correct BOOST_FOREACH usage?
However, my returned list is wrapped in a boost::shared_ptr. If I do not assign the list to a variable before the BOOST_FOREACH loop, I get a crash at runtime as the list is getting destructed as it is a temporary.
boost::shared_ptr< list<int> > GetList()
{
boost::shared_ptr< list<int> > myList( new list<int>() );
myList->push_back( 3 );
myList->push_back( 4 );
return myList;
}
Then later..
// Works if I comment out the next line and iterate over myList instead
// boost::shared_ptr< list<int> > myList = GetList();
BOOST_FOREACH( int i, *GetList() ) // Otherwise crashes here
{
cout << i << endl;
}
I would like to be able to use the above without having to introduce a variable 'myList'.
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,shared_ptr 的“最佳实践”提到避免使用未命名的临时对象:
http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm#BestPractices
Ok, the 'Best Practice' for shared_ptr mentions to avoid using unnamed temporaries:
http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm#BestPractices
您需要使用:
示例:
问题是您无法取消引用 boost::shared_ptr 并希望它返回它存储的底层对象。如果这是真的,那么就无法取消对 boost::shared_ptr 的指针的引用。您需要使用专门的 ::get() 方法返回 boost::shared_ptr 存储的对象,然后取消引用它。
请参阅http://www.boost.org/doc/ libs/1_46_1/libs/smart_ptr/shared_ptr.htm#get 查看文档。
You need to use:
Example:
The problem is that you can't dereference a boost::shared_ptr and hope it returns the underlying object it stores. If this was true, then there would be no way to dereference a pointer to a boost::shared_ptr. You need to use the specialized ::get() method to return the object stored by boost::shared_ptr, and then dereference that.
See http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/shared_ptr.htm#get for the documentation.