【问题标题】:Smart pointers: no suitable constructor exists to convert from derived_object* to std::shared_ptr<abstract_base_object>智能指针:不存在合适的构造函数来从 derived_object* 转换为 std::shared_ptr<abstract_base_object>
【发布时间】:2020-05-10 12:57:25
【问题描述】:

我刚刚开始学习智能指针,但在实现它们时遇到了一些麻烦。

我正在为一个棋盘游戏编写代码,该棋盘游戏有一个抽象的棋子基类,例如一个棋子的派生类:

class pieces {
public:
    virtual ~pieces() {};
};
class piece1:public pieces {
private:
    std::string id{ "" };
    std::string team{ "" };
public: 
    piece1(std::string identification, std::string red_or_blue_team);
    ~piece1() { std::cout << "destructor called." << std::endl; }
};

棋盘游戏本身也有一个单独的抽象类,例如某些特定棋盘游戏的派生类,例如国际象棋:

typedef std::map < int, std::shared_ptr<pieces> > grid;

class board_game {
protected:
    grid the_board;
public:
    virtual std::shared_ptr<pieces> create_piece(std::string type, int id, std::string team) = 0;
};
class chess: public board_game {
public:
    std::shared_ptr<pieces> create_piece(std::string type, int id, std::string team);
};

目标是创建指向映射容器上的值的共享指针,然后随着类中的其他方法移动该块(未显示),该指针将在所有权中移动。

所以作为一个起点,我有函数 create_piece:

std::shared_ptr<pieces> chess::create_piece(std::string type, int id, std::string team)
{
    if (type == "piece1_type") {
        return new piece1(id,team);
    }
}

这会在return new piece1(id,team); 行返回错误 错误(活动)E0415 不存在合适的构造函数来从“piece1*”转换为“std::shared_ptr” 并且 : 'return': 无法从 'flag *' 转换为 'std::shared_ptr'。

我认为解决此问题的方法与更改我对 piece1 的参数化构造函数的实现有关,但我真的不知道该怎么做。 piece1 的构造函数:

flag::flag(std::string identification, std::string red_or_blue_team)
{
    id = identification;
    team = red_or_blue_team;

}

我在这里看到了类似的article,但我无法将其有效地应用于我自己的问题。

【问题讨论】:

    标签: c++ c++11 visual-c++


    【解决方案1】:

    将原始指针隐式转换为智能指针会导致许多潜在问题,例如指向已由智能指针拥有/管理、具有自动存储持续时间或手动管理的内存的原始指针将传递给智能指针进行管理,这将导致双重释放。

    目前不允许这样的隐式“转换”。

    你应该写return std::make:shared&lt;piece1&gt;(id,team);而不是return new piece1(id,team);

    如果你真的想使用智能点来管理原始指针的内存,那么这必须明确地完成std::smart_ptr&lt;piece1&gt;(rawPointer)。这种显式转换通常仅在您使用不使用智能指针并向您返回拥有原始指针的库时才需要。永远不要对您在代码中创建的对象执行此操作。

    【讨论】:

    • 谢谢你的作品!我有一个后续问题,我想知道您是否可以回答。有没有其他(更好的)方法可以设计我的程序,这样我就不必使用 make_shared 或者 make_shared 是完成此类事情的标准方式吗?
    • @user3626437 make_shared 是创建共享指针的标准方式。
    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2017-07-04
    相关资源
    最近更新 更多