下面是一个从包含智能指针的类继承的简单示例。我们什么也不做,只要申报就行了。
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是不是这里的错。虽然C++看起来不错,但我可能以一种奇怪的方式使用了智能指针/虚拟析构函数,因为我对智能指针并不那么熟悉。
如果我使用std::shared_ptr
而不是std::unique_ptr
,则不会引发错误。
发布于 2020-05-13 00:49:16
正如S.M.所暗示的,如果我们必须使用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.
https://stackoverflow.com/questions/61764195
复制相似问题