由于从 std::map 派生的 class 中的 std::map 迭代器导致内存错误
Memory error due to std::map iterator in a class derived from std::map
我从 std::map 派生了一个 class,因为我希望为这个数据结构创建我自己的方法。我遇到了 "mySelect" 的问题,如果该元素不存在,它应该 return nullptr,否则 unique_ptr。
我试过在声明迭代器之前指定 typename 关键字,但没有成功。
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);
}
}
我收到这个错误:
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 &'
首先是这段代码:
return std::make_unique<ValueType>(value);
在逻辑上等于:
std::unique_ptr<ValueType> tmp = new Value(value);
return tmp;
(虽然不一样所以你不应该用一个替换另一个,只是为了让你理解)。因此,您正在尝试创建 class Value
的新实例并从迭代器对其进行初始化。除非 Value
提供这样的构造函数,否则这是行不通的。如果您想制作副本并 return 它并转让所有权,请将您的代码更改为:
return std::make_unique<ValueType>(value->second);
但我不确定这是你想要做的。如果你想 return 一个指向现有对象的指针,你不能在这里使用 std::unique_ptr
因为它提供了唯一的所有权(名称),你需要在你的地图中存储 std::shared_ptr
而不是对象的值和 return 它的一个副本,或者只是 return 一个原始指针。
How is it possible to make the caller of mySelect() to become the owner of the returned object?
或者正如我所说,您通过 std::shared_ptr
存储对象并与此方法的调用者共享所有权,或者您最初将对象存储为 std::unique_ptr
但随后您必须将其移出,因为您std::map
将无法再拥有该对象。
我从 std::map 派生了一个 class,因为我希望为这个数据结构创建我自己的方法。我遇到了 "mySelect" 的问题,如果该元素不存在,它应该 return nullptr,否则 unique_ptr。
我试过在声明迭代器之前指定 typename 关键字,但没有成功。
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);
}
}
我收到这个错误:
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 &'
首先是这段代码:
return std::make_unique<ValueType>(value);
在逻辑上等于:
std::unique_ptr<ValueType> tmp = new Value(value);
return tmp;
(虽然不一样所以你不应该用一个替换另一个,只是为了让你理解)。因此,您正在尝试创建 class Value
的新实例并从迭代器对其进行初始化。除非 Value
提供这样的构造函数,否则这是行不通的。如果您想制作副本并 return 它并转让所有权,请将您的代码更改为:
return std::make_unique<ValueType>(value->second);
但我不确定这是你想要做的。如果你想 return 一个指向现有对象的指针,你不能在这里使用 std::unique_ptr
因为它提供了唯一的所有权(名称),你需要在你的地图中存储 std::shared_ptr
而不是对象的值和 return 它的一个副本,或者只是 return 一个原始指针。
How is it possible to make the caller of mySelect() to become the owner of the returned object?
或者正如我所说,您通过 std::shared_ptr
存储对象并与此方法的调用者共享所有权,或者您最初将对象存储为 std::unique_ptr
但随后您必须将其移出,因为您std::map
将无法再拥有该对象。