gpt4 book ai didi

c++ - 发布 boost::ptr_vector,不匹配文档

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:57 26 4
gpt4 key购买 nike

我正在使用 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();

我试过:

#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

这是 boost 文档中的一个小故障吗?我可以获取 auto_ptr 和取消引用以取回 ptr_vector 吗?

最佳答案

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

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

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

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

注意显式

关于c++ - 发布 boost::ptr_vector,不匹配文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2277898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com