[英]Replace std::vector's buffer with a malloc'ed char array
I have the following class holding an std::vector
as a resizable "buffer" for data.我有以下类将
std::vector
作为数据的可调整大小的“缓冲区”。
class packet
{
public:
struct PacketHeader
{
size_t dataSize = 0;
size_t paddedDataSize = 0;
} header_;
const unsigned char* data() const
{
return &data_[0];
}
unsigned char* data()
{
return &data_[0];
}
/// changes the size of the data vector
void resize(size_t sz)
{
header_.dataSize = sz;
// check if padding is needed
if (sz % AES_BLOCK_SIZE != 0){
auto padding = AES_BLOCK_SIZE - (sz % AES_BLOCK_SIZE);
data_.resize(sz + padding);
for (int i = 1; i <= padding; i++)
{
data_[(sz + padding) - i] = '\0';
}
header_.paddedDataSize = sz + padding;
} else{
data_.resize(sz);
}
}
private:
std::vector<unsigned char> data_;
};
Then I'm performing some AES encryption on the data before transfering them over the network, which requires another temporary buffer of the same size to generate the ciphertext, which then has to be copied back into the vector.然后我在通过网络传输数据之前对数据执行一些 AES 加密,这需要另一个相同大小的临时缓冲区来生成密文,然后必须将其复制回向量中。
void TcpConnection::send_packet(packet& pkg)
{
// I cut out all the unrelevant lines of code
// We need a temporary buffer for the encryption
unsigned char* enc_out = (unsigned char*)malloc(pkg.header_.paddedDataSize);
// AES-128 bit CBC encryption
aes_cbc_encrypt(pkg.data(), enc_out, pkg.header_.paddedDataSize);
// now I need to copy all the data back from the temporary buffer into the objects vector
memcpy(pkg.data(), enc_out, pkg.header_.paddedDataSize);
free(enc_out);
io_service_.post([this, pkg]() { transmit(pkg); });
}
This seems like a rather expensive task.这似乎是一项相当昂贵的任务。 Isn't there a better way, to kind of let the vector take ownership of the temporary buffer (did I understand it correctly that these new
std::move
and rvalue move semantics are used for this kind of stuff?)没有更好的方法,让向量获得临时缓冲区的所有权(我是否正确理解这些新的
std::move
和右值移动语义用于此类内容?)
Move semantics can help avoid the copy.移动语义可以帮助避免复制。
However instead of malloc'ing the buffer for the encrypted data, use a vector.然而,不是 malloc'ing 加密数据的缓冲区,而是使用向量。 You can then use
std::move
to replace the contents of the packet
's data_
member.然后,您可以使用
std::move
替换packet
的data_
成员的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.