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

kev*_*vbo 4 c++ boost ptr-vector

我正在使用boost 1.37,我正在尝试使用boost :: ptr_vector,并转移它的所有权,以便我可以从函数返回它.查看boost文档(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();    
Run Code Online (Sandbox Code Playgroud)

我试过了:

#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;
Run Code Online (Sandbox Code Playgroud)

}

编译器错误:

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
Run Code Online (Sandbox Code Playgroud)

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

Pav*_*aev 6

是的,这是一个文档错误.与auto_ptr(以及具有所有权转移语义的任何其他类型)一样,传输构造函数ptr_dequeexplicit,因此您不能使用=初始化形式.你必须做:

boost::ptr_vector<Item> items(cls.getData());
Run Code Online (Sandbox Code Playgroud)

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

 explicit reversible_ptr_container( std::auto_ptr<reversible_ptr_container> r );
Run Code Online (Sandbox Code Playgroud)

注意explicit.