7

我正在做与此项目类似的事情正确的 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”。这可能吗?

4

2 回答 2

2

好的,shared_ptr 的“最佳实践”提到避免使用未命名的临时对象:

http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm#BestPractices

避免使用未命名的 shared_ptr 临时对象来节省输入;要了解为什么这是危险的,请考虑以下示例:

void f(shared_ptr<int>, int); int g();

void ok() {
    shared_ptr<int> p(new int(2));
    f(p, g()); }

void bad() {
    f(shared_ptr<int>(new int(2)), g()); }

函数 ok 遵循信中的准则,而 bad 构造临时 shared_ptr 就地,承认内存泄漏的可能性。由于函数参数以未指定的顺序进行评估,因此可能首先评估 new int(2),然后评估 g(),如果 g 抛出异常,我们可能永远无法访问 shared_ptr 构造函数。

上述异常安全问题也可以通过使用 boost/make_shared.hpp 中定义的 make_shared 或 allocate_shared 工厂函数来消除。这些工厂功能还通过合并分配提供了效率优势。

于 2011-07-04T19:24:41.547 回答
0

你需要使用:

T* boost::shared_ptr<T>::get()

例子:

BOOST_FOREACH( int i, static_cast< list<int> >( *(GetList().get()) ) ) {

}

问题是您不能取消引用 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

于 2011-07-04T16:04:52.130 回答