我有一个通用数组类,如果与非基本类型一起使用,它会抛出logic_error
。
模板类:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
#define NULL_ELEMENT ((T)NULL)
template<class T> class Array
{
public:
Array(const int size)
{
this->elements[size];
this->size = size;
::fill_n(elements, size, NULL_ELEMENT); /* 1 */
}
// Output of the array
string toString()
{
int i=0;
stringstream ss;
ss << "Array{ ";
for( ; i<size-1; i++ )
{
ss << elements[i] << ", ";
}
ss << elements[i] << " }";
return ss.str();
}
// ...
private:
int size;
T elements[];
};
测试代码:
工作(使用原始类型):
Array<int> arr(5);
cout << arr.toString() << endl;
数组填充0
:Array{ 0, 0, 0, 0, 0 }
失败(使用非原始类型):
Array<string> arr(size); // <-- Exception thrown here
cout << arr.toString() << endl;
抛出异常:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
当调用 ::fill_()
时,这会发生在 Array
类中 (/* 1 */
)。
我想用 T
类型的 Null-Element 填充整个数组(例如,如果 int 则为 0,如果指针则为 NULL
等) - 无需迭代每个元素元素。 memset()
在这里不是一个好的解决方案,不是吗?
最佳答案
这是你应该做的。这是具有正确类骨架的最少代码。
template<class T>
class Array
{
T *m_elements; //declare a pointer member
size_t m_size; //count of the elements
public:
Array(size_t size) : m_size(size), m_element(new T[size]())
{ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// use member-initialization-list
}
~Array(); //must define it
Array(Array const & other); //must define it
Array& operator=(Array const & other); //must define it
Array(Array&& temporary); //better define it (in C++11)
Array& operator=(Array&& temporary); //better define it (in C++11)
//other
};
要知道为什么必须定义析构函数、复制构造函数和复制赋值,更好地定义 移动构造函数和移动赋值,请参阅这些(按顺序):
关于c++ - 如果使用非基本类型,则清除泛型数组会引发逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14176888/