C++ 由std::map派生的类中的std::map迭代器导致内存错误
我正在从std::map派生一个类,因为我希望为这个数据结构创建自己的方法。我对“mySelect”有问题,如果元素不存在,它应该返回null ptr,否则返回unique\u ptr 我尝试在声明迭代器之前指定typename关键字,但没有效果C++ 由std::map派生的类中的std::map迭代器导致内存错误,c++,dictionary,templates,std,C++,Dictionary,Templates,Std,我正在从std::map派生一个类,因为我希望为这个数据结构创建自己的方法。我对“mySelect”有问题,如果元素不存在,它应该返回null ptr,否则返回unique\u ptr 我尝试在声明迭代器之前指定typename关键字,但没有效果 template <class KeyType, class ValueType> class Container : public std::map<KeyType, ValueType> { public:
template <class KeyType, class ValueType>
class Container : public std::map<KeyType, ValueType> {
public:
std::unique_ptr<ValueType> mySelect(KeyType key) {
typename map<KeyType, ValueType>::iterator value;
if ((value = this->find(key)) == this->end())
return nullptr;
return std::make_unique<ValueType>(value);
}
}
模板
类容器:公共std::map{
公众:
std::unique_ptr mySelect(键类型键){
typename映射::迭代器值;
如果((value=this->find(key))==this->end())
返回空ptr;
返回标准::使_唯一(值);
}
}
我得到了这个错误:
Error C2664 'std::vector<std::shared_ptr<Transaction>,std::allocator<_Ty>>::vector(const std::vector<_Ty,std::allocator<_Ty>> &)': cannot convert argument 1 from 'std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>' to 'const _Alloc &'
错误C2664'std::vector::vector(const std::vector&'):无法将参数1从'std::_Tree\u iterator'转换为'const\u Alloc&'
首先,这些代码:
return std::make_unique<ValueType>(value);
但我不确定这是你想要做的。如果要返回指向现有对象的指针,不能在此处使用std::unique_ptr
,因为它提供了唯一的所有权(名称),您需要在地图中存储std::shared_ptr
,而不是按值存储对象并返回其副本,或者只返回原始指针
如何使mySelect()的调用方成为返回对象的所有者
正如我所说,您通过
std::shared\u ptr
存储对象并与此方法的调用方共享所有权,或者您最初将对象存储为std::unique\u ptr
,但随后您必须将其移出,因为您的std::map
将无法再拥有该对象。这std::make\u unique(值)是什么
假设这样做?这不是你的问题,但值得一读:它应该返回一个唯一的\u ptr,指向迭代器找到的类型value的值。你能提供一个吗?显示您的容器的使用方式。这样您就完全走错了路。1-std::make_unique
创建一个新实例。2-std::unique\u ptr
提供所有权。3-尝试创建一个新实例并从迭代器初始化它
std::unique_ptr<ValueType> tmp = new Value(value);
return tmp;
return std::make_unique<ValueType>(value->second);