智能指针:没有合适的构造函数可以从 derived_object* 转换为 std::shared_ptr<abstract_base_object>

Smart pointers: no suitable constructor exists to convert from derived_object* to std::shared_ptr<abstract_base_object>

本文关键字:object std 转换 shared lt gt base abstract ptr 智能 构造函数      更新时间:2023-10-16

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

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

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" 还有 : "返回":无法从"标志*"转换为"标准::shared_ptr"。

我认为这个问题的解决方案与更改 piece1 的参数化构造函数的实现有关,但我真的不确定该怎么做。 piece1 的构造函数:

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

我在这里看到过一篇类似的文章,但我无法有效地将其应用于我自己的问题。

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

因此,这种隐含的"转换"是不允许的。

而不是return new piece1(id,team);你会写return std::make:shared<piece1>(id,team);

如果您真的想使用智能点管理原始指针的内存,则必须std::smart_ptr<piece1>(rawPointer)显式完成。通常,仅当您使用不使用智能指针并向您返回拥有原始指针的库时,才需要此显式转换。切勿对在代码中创建的对象执行此操作。