C++类运行时错误 我尝试为C++做自己的列表。 我有这门课: template <class T> class List { private: T *value, *valueHelper; int valueSize; public: int size; List() { valueSize = 2; value = (T*)malloc(sizeof(T) * valueSize); size = 0; } void Add(T val) { size++; if (size > valueSize) { valueSize *= 2; valueHelper = (T*)malloc(sizeof(T) * valueSize); memcpy(valueHelper, value, sizeof(T) * (valueSize / 2)); free(value); value = valueHelper;; } value[size - 1] = val; } T operator[](int P) { return value[P]; } };
为什么?您的代码中至少有两个错误:C++类运行时错误 我尝试为C++做自己的列表。 我有这门课: template <class T> class List { private: T *value, *valueHelper; int valueSize; public: int size; List() { valueSize = 2; value = (T*)malloc(sizeof(T) * valueSize); size = 0; } void Add(T val) { size++; if (size > valueSize) { valueSize *= 2; valueHelper = (T*)malloc(sizeof(T) * valueSize); memcpy(valueHelper, value, sizeof(T) * (valueSize / 2)); free(value); value = valueHelper;; } value[size - 1] = val; } T operator[](int P) { return value[P]; } };,c++,list,runtime-error,C++,List,Runtime Error,为什么?您的代码中至少有两个错误: - you cannot use memcpy to move class memory from one place to another except in very few cases. a std::string is not one of these cases. - When you call an operator= it needs that the receiver is well formed, and it means that it i
- you cannot use memcpy to move class memory from one place to another except in very few cases. a std::string is not one of these cases.
- When you call an operator= it needs that the receiver is well formed, and it means that it is construct.
您遇到了第二个错误,因为值[0]从来都不是构造的,当您调用运算符=,它将被垃圾填充,并且很可能尝试删除随机指针值
我想您更喜欢只在需要时构造对象,就像std::vector一样?因此,更好的实施方式是:
template <class T>
class List {
int m_size;
int m_capacity;
T * m_elems;
public:
List() :
m_size(),
m_capacity( 2 ),
m_elems( (T*) malloc( sizeof(T) * m_capacity ) ) {
}
void Add( T const & val ) {
if ( m_size + 1 > m_capacity ) {
m_capacity *= 2;
T * elems = (T*) malloc( sizeof(T) * m_capacity );
for( int i = 0 ; i != m_size ) {
new ( elems + i ) T( m_elems[i] ); // copy constructor
( m_elems + i )->~T(); // manually call the destructor
}
free( m_elems );
m_elems = elems;
}
new( m_elems + m_size++ ) T( val );
}
T operator[](int P) {
assert( P < m_size );
return m_elems[P];
}
};
这是因为我没有注意到您原始代码中的第三个错误!运算符[]需要通过引用而不是通过值返回
T & operator[](int P) {
assert( P < m_size );
return m_elems[P];
}
您可能也需要const版本
T const & operator[](int P) const {
assert( P < m_size );
return m_elems[P];
}
首先从MALOC/C++中删除这个整体,并使用new /Malcor Dele[[]。为什么new和DELL更好?@ USER2020928,因为这是C++@ Belz,这不是答案。不,不是因为这是C++。主要是因为new调用构造函数。但是,在这种情况下,正在创建一个数组,所以我不确定这是否是问题所在。嗯,仍然是相同的问题
T & operator[](int P) {
assert( P < m_size );
return m_elems[P];
}
T const & operator[](int P) const {
assert( P < m_size );
return m_elems[P];
}