다음은 스마트 포인터를 포함하는 클래스에서 상속하는 간단한 예입니다. 우리는 그것에 대해 아무것도하지 않고 단지 선언합니다.
import cppyy
cppyy.cppdef("""
class Example {
private:
std::unique_ptr<double> x;
public:
Example() {}
virtual ~Example() = default;
double y = 66.;
};
""")
class Inherit(cppyy.gbl.Example):
pass
a = Inherit()
print(a.y) # Test whether this attribute was inherited
예제가 실행되지만 스마트 포인터에 대한 오류가 있습니다.
input_line_19:9:43: error: call to implicitly-deleted copy constructor of '::Example'
Dispatcher1(const Dispatcher1& other) : Example(other), m_self(other.m_self, this) {}
^ ~~~~~
input_line_17:4:29: note: copy constructor of 'Example' is implicitly deleted because field 'x' has a deleted copy constructor
std::unique_ptr<double> x;
^
/usr/include/c++/7/bits/unique_ptr.h:383:7: note: 'unique_ptr' has been explicitly marked deleted here
unique_ptr(const unique_ptr&) = delete;
^
smart_ptr.py:14: RuntimeWarning: no python-side overrides supported
class Inherit(cppyy.gbl.Example):
66.0
그럼에도 불구하고 C ++ 클래스에서 공용 변수에 액세스 할 수 있으므로 상속이 작동하는 것으로 보입니다. 사실, 나는 cppyy가 여기서 잘못되었는지 100 % 확신하지 못합니다. C ++는 괜찮아 보이지만, 스마트 포인터에 대한 경험이 없기 때문에 이상한 방식으로 스마트 포인터 / 가상 소멸자를 사용하고있을 수 있습니다.
std::shared_ptr
대신 a 를 사용하면 오류가 발생하지 않습니다 .std::unique_ptr
SM에서 알 수 있듯이를 사용해야한다면 unique_ptr
복사 생성자를 정의하는 것이 트릭 인 것 같습니다. 예를 들어이 예제는 오류 메시지없이 예상 된 결과를 제공합니다.
import cppyy
cppyy.cppdef("""
class Example {
std::unique_ptr<double> x;
public:
Example() { x = std::unique_ptr<double>(new double(123.)); }
// Copy constructor
Example(const Example& other) : x(other.x ? nullptr : new double(*other.x)) {}
virtual ~Example() = default;
double y = 66.;
double get_x() { return *x; }
};
auto e = Example();
auto f = e;
""")
class Inherit(cppyy.gbl.Example):
pass
a = Inherit()
print(a.get_x()) # prints 123.
print(a.y) # prints 66.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다