【问题标题】:How to pass one static object around multiple classes?如何在多个类中传递一个静态对象?
【发布时间】:2014-10-15 18:26:24
【问题描述】:

在我的程序中实现 ImageManager 时遇到问题。我成功地使用了这种方法和参考:

//definition in Brick.h
ImageManager &imgr;

//constructor taking &imgr as a reference upon creation of object
Brick::Brick(ImageManager &im) : imgr(im){
//imgr is now a reference in my class, so it points to the same object that imgr in another class would point to
//this essentially makes one "static" instance of imgr, so all my graphic objects are dealing with the same instance of my ImageManager
    imgr.doStuff()
}

这种传递我的 imgr 的方法曾经有效,直到我开始尝试从向量中删除对象。例如,在我的 Level 类中,我尝试从 Brick 对象的向量中删除元素,

void Level::RemoveLine(int line){
    //loop through every piece, loop through given piece's rects, if the rect falls on the removed line, then remove the piece
    for(int i = 0; i < gamePieces_.size(); i++){
        //crt new iterator per each gamepiece
        auto write = gamePieces_[i].GetPieceRectangles().begin();
        int j = 0;
        for(auto read = write; read != gamePieces_[i].GetPieceRectangles().end(); read++){
            if(gamePieces_[i].GetPieceRectangles()[j].GetActiveLine() != line){
                if(read != write){
                    write = std::move(read);
                }
                write++;
            }
        }
        gamePieces_[i].GetPieceRectangles().erase(write, gamePieces_[i].GetPieceRectangles().end());
    }
}

但这不起作用,因为在Brick.h 中声明的ImageManager &amp;imgr 没有复制构造函数,因此当我尝试 .erase() 元素时,它无法复制到向量中。我的目标是实现一个静态 ImageManager 对象,以便在我的所有课程中使用。我该怎么做呢?

【问题讨论】:

  • 如果您尝试摆脱全局 ImageManager(这很好),请使用 std::shared_ptr,您可以轻松地传递它。
  • 嗯,我的尝试是让它全球化,真的,但我明白你的意思。我实际上将引用定义 ImageManager &amp;imgr 切换为指针 ImageManager *imgr 并相应地更改了 imgr 的所有实例。那很好还是我应该实现一个 std::shared_ptr?

标签: c++ vector reference static


【解决方案1】:

“我的目标是实现一个静态 ImageManager 对象,以便在我的所有类中使用”

您可以将 ImageManager 实现为 Singleton 类。但我学会了只有在别无选择的情况下才使用单例。

您还可以在类中使用静态数据成员。这样一来,您班级的数据成员就只有一份副本在流通。

【讨论】:

  • 全局是全局的,不管它是单例、静态成员还是任何全局成员变量。
  • @DieterLücking stackoverflow.com/questions/1463707/…。没有明确的答案哪个更好,但静态比单例有一些优势。
【解决方案2】:

一般来说这种代码不是你想要的。看看Singleton 设计模式。

https://en.wikipedia.org/wiki/Singleton_pattern

【讨论】:

  • 这并没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
  • 其实它确实回答了他的问题。它指出直接答案不是他应该追求的(即直接答案在 99.9% 的情况下是反模式),其次,如果他想要一个单一的、静态的、结构化的可访问实例无论从哪里,都有一个模式,它被称为“Singleton”。
  • “这种代码不是你想要的”听起来你在和发布问题的人争论,这表明这不是一个答案,但也许是一个批评最好留下评论。无论哪种方式,@BrianCarlton 都是正确的 - 这似乎是一个仅链接的答案,即使它不是,正如我断言的那样,评论。
猜你喜欢
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-08
  • 1970-01-01
  • 2016-05-30
  • 2022-12-04
相关资源
最近更新 更多