rudicangiotti
rudicangiotti

Reputation: 566

Questions about pointers inside classes

Considering this class:

class Packet {
public:
  Packet();
  ~Packet();
  void allocateBuffer(unsigned int size);
  void deallocateBuffer();
  char* getBuffer() const;
private:
  char* buffer;
};

With the following methods:

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

Here are some questions:

  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.
  2. if not, can you suggest more elegant ways to do that?

Upvotes: 3

Views: 231

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

  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.

You should always take care of initialization of non static member variables in your class constructor, unless these are non primitive types, and these take care of their initialization themselves.
Accessing them would expose undefined behavior otherwise.

You should note that there's no default initialization for non static class member variables.

Also with c++ you should use nullptr rather than NULL to initialize raw pointers.

  1. if not, can you suggest more elegant ways to do that?

Sure, simply use a std::vector<char> member variable, which will do all the allocation / deallocation memory management automatically for you.

To access the raw data by means of a raw pointer use the std::vector::data() function overloads.

As you mentioned in comments you have to deal with TCP/IP low level API1, I'd recommend you use a std::vector<uint8_t> for the buffering, since you can't be sure that only valid singned char values will be transmitted.


1)When dealing with data sent over the wire, take care of machine endianess neutrality, especially when sending and receiving packet sizes. The htonx() / ntohx() function family comes in handy to do that correctly.

Upvotes: 6

Related Questions