首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >继承包含智能指针的类。

继承包含智能指针的类。
EN

Stack Overflow用户
提问于 2020-05-13 00:15:03
回答 1查看 201关注 0票数 2

下面是一个从包含智能指针的类继承的简单示例。我们什么也不做,只要申报就行了。

代码语言:javascript
运行
复制
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

此示例运行,但与智能指针有关的错误。

代码语言:javascript
运行
复制
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,则不会引发错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-13 00:49:16

正如S.M.所暗示的,如果我们必须使用unique_ptr,诀窍似乎是确保定义一个副本构造函数,例如,这个示例给出了没有错误消息的预期结果,

代码语言:javascript
运行
复制
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.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61764195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档