unordered_map (A)constructor, (B) delete allocate in, (C)inh
unordered_map (A)constructor, (B) delete allocate in, (C)inherit from
当Comparison
是类名时,我的声明是unordered_map<Comparison,int> Chs
。现在我有几个问题;
。当构造函数调用时,我如何插入一些元素(如vector
) ?
。:
unordered_map<Comparison,int> Chs =
{
(new Equal_to<int>,10),
(new Not_equal_to<int>,30),
(new Greater<int>,20)
};
这段代码现在得到编译错误。
B。如何释放分配的内存(与new
)在这个声明?
C。在继承类:
template <class T,class V>
class RC : public unordered_map<T, V>
我应该如何编写RC
构造函数,使其可以初始化的元素,如一个问题?
谢谢你,很抱歉我的英语很差。
你最好不要继承标准容器,它们不是为它设计的。
此外,如前所述,要使包含的比较具有多态行为,您需要存储引用或指针。指针的使用要简单得多。为了避免担心释放内存,使用智能指针(std::unique_ptr或std::shared_ptr)。
下面的代码片段显示了上述大部分代码的工作原理,包括如何在自己的容器类(RC<>
)上进行统一初始化:
#include <unordered_map>
#include <memory>
struct Comparison {};
template <class T> struct Equal_to : Comparison { };
template <class T> struct Not_equal_to : Comparison { };
template <class T> struct Greater : Comparison { };
template <class T,class V>
class RC
{
typedef std::unordered_map<T,V> comps_t;
typedef typename comps_t::value_type value_type;
comps_t comps;
public:
RC(std::initializer_list<value_type> init) : comps(init) { }
};
int main(int argc, const char *argv[])
{
RC<std::shared_ptr<Comparison>, int> demo = {
{ std::make_shared<Equal_to<int>>(),10 },
{ std::make_shared<Not_equal_to<int>>(),30 },
{ std::make_shared<Greater<int>>(),20 } };
return 0;
}
在(可能无用的优化)部门,如果它不与其他构造函数需求冲突,您可以拥有完美的转发构造函数。这将有利于正确地支持move语义:
template <typename... A>
RC(A&&... a) : comps(std::forward<A...>(a...)) { }
相关文章:
- 模式"allocate memory or use existing data"
- 为什么'allocate in one library and free in the other'是错误的
- 使用 system(命令) 时,C++代码在 AWS 中失败,并出现错误"cannot allocate memory"
- 对"cv::String::allocate(unsigned long)"的未定义引用
- 加载共享库时未定义的符号"tbb internal Allocate"
- 如何测试分配器是否使用std::allocate进行内存分配
- 科学实验室编译"cannot allocate this quantity of memory"
- 抽象类和虚方法问题:"cannot allocate an object of abstract type"
- 为什么我会得到"cannot allocate an array of constant size 0"?
- unordered_map (A)constructor, (B) delete allocate in, (C)inh
- malloc和allocate的区别是什么?
- "STL allocate memory internally"是什么意思?
- 是否保证std::vector每次使用allocate函数分配的内存,也会通过单个deallocate调用立即释放?
- STL容器库-在allocator类的不同实例上调用allocate/deallocate是否合法?
- 重载操作符new / allocate大于对象大小
- 纯虚拟功能和"cannot allocate an object"
- 为什么 Linux msync 会返回"Cannot Allocate memory"?是否可以修复此错误代码?
- 单独的 allocate() 定义会导致自定义分配器C++"undefined reference"链接错误