我创建了一个 vector 类对象。以下程序崩溃
"Pointer being freed was not allocated".
我也深深地复制了。我看不到双重删除在哪里发生。我想念什么?
#include <iostream>
#include <vector>
using namespace std;
enum MessageType { HEADER, DATA, CLOSE};
typedef class bufferElement{
public:
char *buffer ; //The actual data
int64_t length; //length of the data
MessageType messagetype;
/**
* Copy constructor for the structure
*/
bufferElement(const struct bufferElement &toCopy)
{
std::cout << "Copying the buffer vector - Copy Constructor for buffer" << std::endl;
buffer = new char[toCopy.length];
memcpy(buffer,toCopy.buffer,toCopy.length);
length = toCopy.length;
messagetype = toCopy.messagetype;
}
bufferElement()
{
buffer = NULL;
length =0;
messagetype = HEADER;
}
/**
* Initialises the vector element
* @param messagetype
* what type of message is the particular element.
* @param element
* The buffer element
* @param length_t
* The length/size of the buffer element
*/
bufferElement(char *element, int64_t length_t, MessageType messagetype_t) //constructor
{
std::cout << "The buffer element is Initialized" << std::endl;
buffer = new char[length_t];
messagetype = messagetype_t;
length = length_t;
memcpy(buffer, element, length_t);
}
~bufferElement()
{
std::cout << "Freeing the buffer in the vector - Destructor" << std::endl;
delete buffer;
buffer = NULL;
}
} messageHolder;
int main()
{
vector<messageHolder> v;
for(int64_t i=0; i< 1000000000000000000; i++)
{
int size = rand()%10000+5;
char *test = new char[size];
messageHolder m(test, size, HEADER );
v.push_back(m);
if(rand()%3)
{
v.erase(v.begin());
}
}
return 0;
}
最佳答案
我没有详细介绍您的代码,但是如果您认为需要复制构造函数,则还需要赋值运算符。而且,为什么,为什么,为什么无论如何都要写这些东西?为什么不使用std::string?您是否需要编写自己的浮点类型?不,我不这么认为。