我最近开始学习c ++(我已经有了c的中级水平).我理解,构造函数背后的想法以及它们是如何工作的,但我不明白为什么当我使用new创建Packet对象时,构造函数中的malloc返回NULL/0x0内存位置.如果我定义一个Packet对象,我对构造函数中的malloc没有任何问题.这是代码,希望格式/编码的任何更正:
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
class Packet
{
public:
unsigned int size_pck;
char *packet_data;
Packet(unsigned int size)
{
size_pck=size;
char *packet_data=(char *)malloc(size);
}
~Packet()
{
free(packet_data);
}
};
int main (void)
{
Packet *created_pck;
created_pck=new Packet(4);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
首先,您要创建一个本地变量 - 而不是分配给您的成员:
Packet(unsigned int size)
{
size_pck=size;
packet_data=(char *)malloc(size);
}
Run Code Online (Sandbox Code Playgroud)
另一方面,在C++中已经有了一种方便的方法来保持动态大小的chars:数组std::vector:
class Packet {
std::vector<char> packet_data;
public:
Packet(unsigned int size)
: packet_data(size)
{ }
};
Run Code Online (Sandbox Code Playgroud)
这具有额外的好处,即在复制时不会泄漏内存Packet.或者,或者,std::unique_ptr<char[]>使用额外大小的成员,以避免初始化chars - 如果这很重要.