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:
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.
- 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.
- 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With