这是我的代码。
std::shared_ptr<WSUStudent> WSUStudent::registerStudent(
std::string lastName,
std::string firstName
)
{
auto result = std::shared_ptr<WSUStudent>(new WSUStudent(lastName, firstName));
s_allStudents.insert(&result);
return result;
}
我已经成功地更改了功能,因此它返回了shared_ptr而不是普通的指针。根据分配(我认为),我已经成功地使用共享指针封装了“ new”语句,但是如果没有&,则“ auto”下面的代码行将不起作用,而与&一起将无法工作。我收到一条错误消息,指出没有匹配的函数调用(带或不带&)。该行代码试图将新学生(或指向新学生的指针?)插入所有学生的列表中。但是,“插入”方法并未在本地被覆盖,因此我不太确定该怎么做。错误打印在下面。
/mnt/hgfs/Data Structures and Algorithms/HW04/WSUStudent.cpp:146:32: error: no matching function for call to ‘std::set<WSUStudent*>::insert(std::shared_ptr<WSUStudent>*)’
s_allStudents.insert(&result);
这种分配的目的是通过将普通指针变为弱指针和共享指针来修复内存泄漏(不会被其指针删除的“新”语句)。原始代码如下。
WSUStudent *WSUStudent::registerStudent(
std::string lastName,
std::string firstName
)
{
auto result = new WSUStudent(lastName, firstName);
s_allStudents.insert(result);
return result;
}
我要解决这个错误吗?我无法运行s_allStudents行。
根据的类型s_allStudents
,您可以使用:
s_allStudents.insert(result.get());
但是,更好的选择是更改的类型s_allStudents
。
static std::set<std::shared_ptr<WSUStudent>> s_allStudents;
并使用:
s_allStudents.insert(result);
更新
默认operator<()
的shared_ptr
是这样的,在对象s_allStudents
将指针的值进行排序。如果要使用其他条件对对象进行排序,则需要定义一个自定义函子/函数作为模板的参数。
struct MyCompare
{
bool operator<(shared_ptr<WSUStudent> const& lhs,
shared_ptr<WSUStudent> const& rhs) const
{
// Implement the logic ...
}
};
并将其用作:
static std::set<std::shared_ptr<WSUStudent>, MyCompare> s_allStudents;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句