Men*_*des 1 c++ vector shared-ptr
我使用以下代码建立一种注册表类:
class MyClass
{
public:
int a;
std::string b;
};
class Register
{
public:
std::vector<std::shared_ptr<MyClass>> items;
bool registerItem(std::shared_ptr<MyClass> item)
{
/*
* Check if item exists
*/
auto position = std::find(items.begin(), items.end(), item);
if (position != items.end())
return false;
items.push_back(item);
return true;
}
bool unregisterItem(std::shared_ptr<MyClass> item)
{
auto position = std::find(items.begin(), items.end(), item);
if (position == items.end())
return false;
items.erase(item);
return true;
}
};
int main()
{
std::shared_ptr<MyClass> item1 = new MyClass;
Register registry;
if (!registry.registerItem(item1))
std::cout << "Error registering item1" << std::endl;
else
std::cout << "Success registering item1" << std::endl;
if (!registry.registerItem(item1))
std::cout << "Error unregistering item1" << std::endl;
else
std::cout << "Success unregistering item1" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
items.erase(item)抱怨,我无法编译这段代码error: no matching member function for call to 'erase'.
为什么我不能删除我添加的对象.std::shared_ptr从a中删除a的正确方法是std::vector什么?
| 归档时间: |
|
| 查看次数: |
2015 次 |
| 最近记录: |