发布boost :: ptr_vector,而不是匹配文档

时间:2010-02-17 02:13:52

标签: c++ boost ptr-vector

我正在使用boost 1.37,我正在尝试使用boost :: ptr_vector,并转移它的所有权,以便我可以从函数返回它。查看增强文档(http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/tutorial.html#new-functions

std::auto_ptr< boost::ptr_deque<animal> > get_zoo()
{
    boost::ptr_deque<animal>  result;
    ...
    return result.release(); // give up ownership
 }
 ...
 boost::ptr_deque<animal> animals = get_zoo();    

我试过了:

#include "iostream"
#include <boost/ptr_container/ptr_vector.hpp>

class Item
{
public:
  int my_val;
  Item() : my_val(0) { }
};

class MyClass
{
private:
  boost::ptr_vector<Item> items_;  

public:
  MyClass() 
  { 
    for (int i = 0; i < 10; ++i)
      items_.push_back(new Item);
  }

  std::auto_ptr<boost::ptr_vector<Item> > getData() { return items_.release(); }
};

int totalItems(boost::ptr_vector<Item> items)
{
  int total = 0;
  boost::ptr_vector<Item>::iterator it;
  for (it = items.begin(); it != items.end(); ++it)
    total += (*it).my_val;
  return total;
}

int main(int argc, char **argv)
{
  MyClass cls;

  boost::ptr_vector<Item> items = cls.getData();

  int total = totalItems(items);

  fprintf(stdout, "I found %d items!\n", total);

  return 0;

}

编译器错误:

In function ‘int main(int, char**)’:
error: conversion from ‘std::auto_ptr<boost::ptr_vector<Item, boost::heap_clone_allocator, std::allocator<void*> > >’ to non-scalar type ‘boost::ptr_vector<Item, boost::heap_clone_allocator, std::allocator<void*> >’ requested

这是增强文档中的一个小故障吗?我可以获得auto_ptr和dereference来获取ptr_vector吗?

1 个答案:

答案 0 :(得分:6)

是的,这是一个文档错误。与auto_ptr(以及具有所有权转移语义的任何其他类型)一样,ptr_deque上的转移构造函数为explicit,因此您无法使用=初始化形式。你必须这样做:

boost::ptr_vector<Item> items(cls.getData());

此外,它只是教程错了;实际的类引用正确显示了这一点。如果你看here,你会看到声明:

 explicit reversible_ptr_container( std::auto_ptr<reversible_ptr_container> r );

注意explicit