我指的是以下链接:https://www.cryptopp.com/wiki/StreamTransformationFilter和https://www.cryptopp.com/wiki/CBC_Mode
在StringSource string_source(encypted_data, true, new StreamTransformationFilter(decryption, new StringSink(plain_data)));
行中,我们使用new
操作符在堆上创建了类StreamTransformationFilter和StringSink的对象;但是我们没有删除它们。它不应该导致内存泄漏,因为它们不是删除操作。
我是否应该更换
StringSource string_source(plain_data, true, new StreamTransformationFilter(encryption, new StringSink(encypted_data)));
使用以下代码
try
{
CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption encryption(this->aes_key.data(), this->aes_key.size(), this->aes_iv.data(), this->aes_iv.size())
CryptoPP::StringSink string_sink(encypted_data);
CryptoPP::StreamTransformationFilter stf_encryptor(encryption, string_sink);
CryptoPP::StringSource string_source(plain_data, true, stf_encryptor);
}
为了避免内存链接,一旦退出try块,类CryptoPP::StringSink
、CryptoPP::StreamTransformationFilter
和CryptoPP::StringSource
上的析构函数就会被调用。
程序:
std::optional<std::string> Cryptography::decrypt_data(const std::string& encypted_data)
{
std::optional<std::string> plain_data { std::nullopt };
try
{
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption decryption(this->aes_key.data(), this->aes_key.size(), this->aes_iv.data(), this->aes_iv.size())
StringSource string_source(encypted_data, true, new StreamTransformationFilter(decryption, new StringSink(plain_data)));
}
catch(const CryptoPP::Exception& e)
{
#ifdef _DEBUG
spdlog::error("CryptoPP Exception in Cryptography::decrypt_data : {}", ex.what());
#endif
PLOG_ERROR << ex.what();
}
catch(const std::exception& ex)
{
#ifdef _DEBUG
spdlog::error("Exception in Cryptography::decrypt_data : {}", ex.what());
#endif
PLOG_ERROR << ex.what();
}
return plain_data;
}
发布于 2020-07-31 13:08:16
当您将过滤器/接收器传递给filer/source的构造函数时,它将获得指针的所有权,并在销毁时将其删除。
在您的示例中,StringSource
删除StreamTransformationFilter
,进而删除StringSink
https://stackoverflow.com/questions/63185888
复制相似问题