我不明白为什么会出现此编译器错误:
这是相关代码:
#pragma once
#include <SFML\Graphics.hpp>
#include "SpawnManager.h"
#include "Resource.h"
#include <stack>
#include <memory>
class GameState;
class Controller
{
public:
Controller();
void run();
void setPlayerScore(unsigned score);
sf::RenderWindow& getWindow() { return m_window; }
void addState(const States& state);
void changeState(const States& state);
GameState* getState() const;
void popState();
void add_state(const States& type, Controller * cont);
~Controller() {}
private:
SpawnManager<States, GameState> m_sFactory;
sf::RenderWindow m_window;
ScoreRecord m_playerScore;
std::stack<std::unique_ptr<GameState>> m_screens;
};
#pragma once
#include <SFML\Graphics.hpp>
#include <memory>
#include "Controller.h"
//State design pattern
class GameState
{
public:
explicit GameState(Controller* state_holder);
GameState(const GameState&) = delete;
GameState(GameState&&) = delete;
GameState& operator=(const GameState&) = delete;
GameState& operator=(GameState&&) = delete;
virtual ~GameState() = default;
virtual void displayState() = 0;
virtual void updateStage() = 0;
virtual void handleEvent(sf::Event& event) = 0;
protected:
std::unique_ptr<Controller> m_state;
};
任何想法如何解决这一问题?
最佳答案
std::unique_ptr<T>
的析构函数的定义要求T
是完整的,即已定义,而不仅仅是声明。由于std::unique_ptr<GameState>
是Controller
的(n个间接成员),所以析构函数~Controller
的定义需要std::unique_ptr<GameState>
的析构函数的定义,因此也需要GameState
的定义(未提供)。
解决方案:在定义GameState
之前,先定义~Controller
。一个最小的例子:
struct GameState;
// 1. Definition of Controller
struct Controller
{
~Controller();
std::stack<std::unique_ptr<GameState>> m_screens;
};
// 2. Definition of GameState
struct GameState
{
std::unique_ptr<Controller> m_state;
};
// 3. Definition of Controller::~Controller
Controller::~Controller(){} // or = default;
P.S.考虑一下,您永远不能让指向同一
GameState
的Controller
指向GameState
。在这种情况下,最终将无限次递归破坏已破坏的对象。并且多个GameStates
不能拥有相同的Controller
,反之亦然。考虑您的所有权结构是否合理。我怀疑您需要共享所有权还是非所有权推荐。关于c++ - 循环依赖: can't delete an incomplete type,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44633726/