c++ - 关于类内部指针的问题

标签 c++ class pointers null

考虑这个类:

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
  }
}

这里有一些问题:

  1. 因为在 C 中指针等于 NULL 如果它们指向任何内容,那么上面列出的实现是处理类内部指针的好方法吗?我问这个是因为如果 buffer 变量没有在构造函数中初始化,一个奇怪的 \v 值似乎默认分配给它。
  2. 如果没有,您能推荐更优雅的方法吗?

最佳答案

  1. 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初始化原始指针。

  1. 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/

相关文章:

c++ - C++ 的模块概念

c++ - 加载 Bazel 扩展失败

python - 像 swift 一样在 python 中进行类扩展?

c++ - C++ 期望数组下标是什么类型?

c - 释放使用双指针分配的结构数组

c - 空数组指针

c++ - fstream 接受文件夹路径并且是 (`good()==1` )

c++ - 我在哪里可以找到 arm-wince-pe-gcc 的二进制文件?

java - 用于计算类实例数量的字段

c++ - 不能使用在另一个 hpp 文件中定义的类