I am writing a Qt C++ application where I am reading a pcap file and interpreting packets described in given file. As I am reading packet by packet, I need to somehow store binary data. It needs to be flexible enough so I can pass it across multiple functions as parameter and being able to work with it as char*
. It also should be safe enough to avoid memory leaks.
I came up with 2 approaches:
1. unique_ptr<char[]>
So basically I can use std::ifstream
for reading from file and storing binary data in std::unique_ptr<char[]>
like so :
std::ifstream ifs(fullFilename.c_str(), std::fstream::binary | std::fstream::in, _SH_DENYNO);
std::unique_ptr<char[]> buff = std::make_unique<char[]>(65535); //size is set according to pcap_hdr_s.snaplen
ifs.read(buff.get(), 65535);
And then passing it to function via raw pointer (void f(const unsigned char* p) => f((unsigned char*)buff.get()))
or via reference (void f(std::unique_ptr<char[]>& p) => f(buff)
)
2. QByteArray
In this approach, I would use QFile
for reading from file and storing data in QByteArray
like this :
QFile file(fileName.c_str());
QByteArray buff;
buff.resize(65535);
file.read(buff.data(), 65535);
And then passing it to the functions via reference ( void f(QByteArray& buff) => f(buff)
).
Which approach is better ? Or do you have some better way of doing this ?
Some notes about Qt:
QByteArray QIODevice::readAll()
directly to obtain a buffer: QFile file(fileName.c_str());
auto buff = file.readAll();
QByteArray
is implicite sharing / copy-on-write. So while you can pass by reference, you should either pass by const reference or simply pass by value.Your solution with std::unique_ptr<>
looks like a good thing to do, but also a bit cumbersome. If your project is already heavily using Qt, I would go for the Qt route.
Passing a reference to a unique_ptr
is also quite unexpected. Either pass the raw pointer/reference (for example to a helper method, that will return while you hold the unique_ptr
), or by moving the unique_ptr
(if you want to transfer ownership). See an explanation here.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments