c++ - 我应该使用哪个智能指针?

标签 c++

我正在反对由许多不同类型(属性、父项、子项等)组成的模型。每种类型都与一组来自 c api 的函数相关联。例如:

Type "Properties":
  char* getName(PropertiesHandle);
  char* getDescription(PropertiesHandle);

Type "Parent"
  PropertiesHandle getProperties(ParentHandle);
  ChildHanlde getFirstChild(ParentHandle);

Type "Child"
  PropertiesHandle getProperties(ChildHandle);
  ParentHanlde getParent(ChildHandle);
  ChildHandle getNextChild(ChildHandle);

我已经为这个c api库依次创建了一套C++接口(interface),如下:

class IProperties
{
public:
  virtual std::string getName() = 0;
  virtual std::string getDescription() = 0;
};

class IParent
{
public:
  virtual std::shared_ptr<IProperties> getProperties() = 0;
  virtual std::shared_ptr<IChild> getFirstChild() = 0;
};

class IChild
{
public:
  virtual std::shared_ptr<IProperties> getProperties() = 0;
  virtual std::shared_ptr<IParent> getParent() = 0;
  virtual std::shared_ptr<IChild> getNextChild() = 0;
};

然后我通过 Properties、Parent 和 Child 类实现这些接口(interface)。

因此,Child 实例将通过其构造函数获取其特定的 ChildHandle,其 getParent 函数将如下所示:

std::shared_ptr<IParent> getParent()
{
    // get the parent handle and wrap it in a Parent object
    return std::shared_ptr<IParent>(new Parent(_c_api->getParent(_handle)));
}

在你看来,我在这里返回一个 shared_ptr 是否合理。我不能使用 std::unique_ptr,因为 Google Mock 要求模拟方法的参数和返回值是可复制的。我通过 Google Mock 在我的测试中模拟这些接口(interface)。

我也在考虑将来如何优化事情,这可能会出现循环引用的可能性。如果使用缓存来避免对 C api 的多次调用(例如,子项不需要多次建立其父项)并结合使用子构造函数获取其父项,则可能会导致这种情况。这将需要使用 weak_ptr,这将改变接口(interface)和我的很多代码......

最佳答案

关键问题是:返回指针的语义是什么?

  • 如果返回的父/子/属性对象的生命周期独立于返回的(大概在某种意义上,拥有)对象,则返回 shared_ptr 是合理的: 这表明调用者和被调用者有平等的权利来决定对象的生命周期

    std::shared_ptr<IChild> child = parent->getFirstChild();
    // now I can keep child around ... if parent is destroyed, one
    // orphaned subtree is magically kept around. Is this desirable?
    
  • 如果返回对象的生命周期依赖于被调用者自己的生命周期,那么:

    • shared_ptr错误地建议调用者将返回对象的生命周期延长到被调用者的生命周期之外是有意义的
    • unique_ptr错误地建议所有权转让
    • 原始指针不会明确做出任何误导性的 promise ,但也不会给出任何正确使用的提示

因此,如果调用者只是获取对象内部状态的工作引用,既没有转移所有权也没有延长对象的生命周期,则不建议使用任何智能指针。 p>

考虑只返回一个引用。

关于c++ - 我应该使用哪个智能指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11828254/

相关文章:

c++ - 比较 C++ 时常量超出范围

c++ - C++ STL 对于不同的容器是否是线程安全的(使用 STLport 实现)?

c++ - 套接字错误 gcc 无法在 WinSock2.h 中获取函数

运算符中的 c++ 空格,规则是什么

c++ - 我的程序中的一个值计算不正确,即使支持的数学是正确的

c++ - 自定义迭代器指向临时对象(延迟加载)

c++ - 在施工期间采用类成员的未初始化引用是否合法?

c++ - 如何配置 autoreconf 使用不同于 GCC 的编译器

c++ - 无法在 Microsoft VC++ Inline ASM 中选择位

c++ - 在文本文件中搜索某个单词 C++