【问题标题】:Why I can't use std::unique_ptr for avoiding circular dependency? [duplicate]为什么我不能使用 std::unique_ptr 来避免循环依赖? [复制]
【发布时间】:2016-12-22 08:28:48
【问题描述】:

这是我的一段代码:

class Model;

class Resources
{
public:
  Resources() :
      initialized(false)
    , pathToSkyBoxModel("E:\\C++\\OpenGLtutorial\\resources\\cube.obj")
{};

  void Init(const ShaderProgram& shaderProgram);

  /* Setters */
  void SetSkyBoxModelPath(std::string&& newPath) { pathToSkyBoxModel = newPath; };

  /* Getters */
  bool IsInitialized() const noexcept { return initialized; };
  const std::string& GetPathToSkyBoxModel() const noexcept { return   pathToSkyBoxModel; };

  DiffuseTexture default_texture;
  TransparentTexture default_transparent_texture;

  private:

  std::unique_ptr<Model> pModel;
  bool initialized;
};

我试图通过对资源类成员 pModel 使用 std::unique_ptr 来避免循环依赖。不幸的是,我收到编译错误,例如:“您不能在此处使用部分定义的类”。但它适用于 std::shared_ptr 和公共指针。 std::unique_ptr 有什么问题?

【问题讨论】:

标签: c++ c++11 stl


【解决方案1】:

问题是编译器试图声明一个内联析构函数,为此它需要类的完整定义。

您可以通过在.h 中声明析构函数并在/.cpp 中定义它来绕过它

//in .h
~Resources();

//in cpp
Resources::~Resources() {} 

【讨论】:

  • 但为什么它适用于 std::shared_ptr ?
  • stackoverflow.com/questions/20985667/…shared_ptr 有一个额外的间接性,因此只有在实际构造/删除对象时才需要知道完整类型。
猜你喜欢
  • 2013-02-06
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
相关资源
最近更新 更多