2016-08-04 5 views
1

래퍼 클래스 이제 I 얻을왜 파이썬이 복사 생성자를 부스트합니까?

obj=Example() 
obj.count().count() 

다음 파이썬 코드를 실행하는 경우

using namespace boost::python; 
class_<Example>("Example", init<>()) 
     .def("count", &Example::count, return_value_policy<copy_non_const_reference>()); 

사용 파이썬 노출

class Example 
{ 
public: 
    Example() 
    { 
     std::cout << "hello\n"; 
    } 
    Example(const Example& e) 
    { 
     std::cout << "copy\n"; 
     counter++; 
    } 
    ~Example() 
    { 
     std::cout << "bye\n"; 
    } 
    Example& count() 
    { 
     std::cout << "Count: " << counter << std::endl; 
     return *this; 
    } 
    static int counter; 
}; 
int Example::counter = 0; 

제공된다 가정

hello 
Count: 0 
copy 
Count: 1 
copy 
bye 

이것은 부스트 ​​파이썬이 복사본 생성자를 사용하고 있음을 의미합니다.

내 질문은 :

  1. 왜 복사 생성자가 호출된다?
  2. boost :: noncopyable을 사용하면 복사 생성자가 호출되지 않습니다. 그러나,이 경우에는 to_python 변환기 (아래 참조)에 대해 불평하면서 파이썬 코드를 실행할 수 없습니다. 이 문제를 해결할 방법이 있습니까?

    오류 : 클래스 예 return_value_policy<copy_non_const_reference>() 설정되고 있기 때문에 복사 생성자가 호출

답변

2

boost docs하여 : 변환기는 C++ 형 검색 결과 없음 to_python (기준 값)

copy_non_const_reference is a model of ResultConverterGenerator which can be used to wrap C++ functions returning a reference-to-non-const type such that the referenced value is copied into a new Python object.

그것을 반환 값을 복사해야하지만 클래스는 noncopyable이므로 기본 변환기를 찾을 수 없으므로 불평합니다.

이 문제를 해결하려면 return_value_policy<copy_non_const_reference>()을 사용하거나 사용자 정의 to_python 변환기를 정의하지 마십시오.

+0

감사합니다. 분명히 boost :: python :: return_self <>() 대신 사용해야합니다. – Amirhessam