gpt4 book ai didi

c++ - 类对象的 vector

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:41 24 4
gpt4 key购买 nike

我创建了一个类对象 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?您觉得有必要编写自己的浮点类型吗?不,我不这么认为。

关于c++ - 类对象的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6313504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com