考虑这个类:
class Packet {
public:
Packet();
~Packet();
void allocateBuffer(unsigned int size);
void deallocateBuffer();
char* getBuffer() const;
private:
char* buffer;
};
通过以下方法:
Packet::Packet():
buffer(NULL) {
std::cout << "[DEBUG] Construct Packet class..." << std::endl;
}
void Packet::allocateBuffer(unsigned int size) {
if (!(buffer)) {
buffer = new char[size];
#ifdef DEBUG
std::cout << "Allocate buffer memory..." << std::endl;
#endif
}
}
void Packet::deallocateBuffer() {
if (buffer) {
delete[] buffer;
buffer = NULL;
#ifdef DEBUG
std::cout << "Deallocate buffer memory..." << std::endl;
#endif
}
}
这里有一些问题:
- 因为在 C 中指针等于
NULL
如果它们指向任何内容,那么上面列出的实现是处理类内部指针的好方法吗?我问这个是因为如果buffer
变量没有在构造函数中初始化,一个奇怪的\v
值似乎默认分配给它。 - 如果没有,您能推荐更优雅的方法吗?
最佳答案
- since in C pointers are equal to NULL if they point to nothing, are the above listed implementations good ways to deal with pointers inside classes? I ask for this because if the buffer variable is not initialised in constructor, a strange \v value seems to be assigned to it by default.
您应该始终注意类构造函数中非静态成员变量的初始化,除非它们是非基本类型,并且它们自己会进行初始化。
否则访问它们会暴露未定义的行为。
您应该注意,非静态类成员变量没有默认初始化。
对于 C++,您还应该使用 nullptr
而不是 NULL
初始化原始指针。
- if not, can you suggest more elegant ways to do that?
当然,只需使用 std::vector<char>
成员变量,它将自动为您完成所有分配/释放内存管理。
要通过原始指针访问原始数据,请使用 std::vector::data()
函数重载。
正如您在评论中提到的,您必须处理 TCP/IP 低级 API1,我建议您使用 std::vector<uint8_t>
用于缓冲,因为您不能确定只有有效的签名 char
值将被传输。
1)处理通过线路发送的数据时,请注意机器字节序中立性,尤其是在发送和接收数据包大小时。 htonx()
/ ntohx()
函数族可以派上用场来正确地做到这一点。
关于c++ - 关于类内部指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506019/