智能指针:没有合适的构造函数可以从 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>
我刚刚开始学习智能指针,我在实现它们时遇到了一些麻烦。
我正在为一个棋盘游戏编写代码,该游戏有一个抽象的棋子基类,例如一个派生类:
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)
显式完成。通常,仅当您使用不使用智能指针并向您返回拥有原始指针的库时,才需要此显式转换。切勿对在代码中创建的对象执行此操作。
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 在<Object>基于范围的 for 循环中从 std::vector 获取指向对象的指针
- 自 C++17 以来使用 std::launder "validate"非"pointer to object"指针值
- C 按其值对object的std ::列表进行排序
- std::find for inherit object c++
- 如何将元素插入 std::unordered_map<int, vector<Object*>>
- 将 v8::Local<v8::Object> 存储在类中 静态 std::vector
- 没有合适的转换函数来自 std::vector<Object *, std::分配器<Object *>> " to " Object *"
- 如何为静态成员编写std::is_member_{object,function}_pointer
- 如何传递lambda, function object或std::function作为模板参数并控制它们的参数
- std::find Object by Member
- C# mashal const std::list<object> from c++ dll
- 类 std::vector<Object> 没有名为 'x' 的成员
- 在同一赋值表达式中使用std::move(object)和object.method()
- 返回 std::vector<std::unique_ptr<Object>的方法>
- 类型为"std::vector<Object*>&"的非常量引用的初始化无效
- std::vector push_back(Object())和push_back(new Object())的区别
- 将Object转换为std::unique_ptr