2010-02-17 2 views
4

부스트 1.37을 사용하고 boost :: ptr_vector를 사용하여 소유권을 이전하려고합니다. 따라서 함수에서 반환 할 수 있습니다. 부스트 설명서를 보면 (http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/tutorial.html#new-functions)boost :: ptr_vector를 공개하지 않고 설명서와 일치하지 않습니다.

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 

이 부스트 문서의 결함인가를? ptr_vector를 다시 얻기 위해 auto_ptr 및 참조 해제를 얻을 수 있습니까?

답변

6

예, 문서 버그입니다. auto_ptr (및 소유권 이전 의미가있는 다른 유형)과 마찬가지로 ptr_deque의 전송 생성자는 explicit이므로 = 초기화 프로그램 양식을 사용할 수 없습니다. 다음을 수행해야합니다.

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

또한 튜토리얼 만 잘못되었습니다. 실제 클래스 참조는이를 올바르게 보여줍니다.

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

explicit : 당신이 here을 보면, 당신은 선언을 볼 수 있습니다.

+0

머리를 주셔서 감사합니다. 이제 모든 것이 작동합니다. – kevbo

관련 문제