Crypto++ explicit destruction during encryption/decryption?

前端 未结 2 1506
独厮守ぢ
独厮守ぢ 2020-12-19 17:26

I wrote some wrapper functions to encrypt/decrypt files using crypto++. I tried looking in the wiki but could find my answer. I am wondering if I need to explicitly destroy

2条回答
  •  庸人自扰
    2020-12-19 17:46

    No, you don't. The objects you create have automatic storage duration, which means their destructor will be automatically invoked at the end of their scope. Moreover, the arguments that you pass with new will be owned by the Crypto++ objects, and their corresponding destructor will release the memory for you. They fall into the category of a sink or a filter, and it turns out that you also pass the ownership. For more details see:

    https://www.cryptopp.com/wiki/Pipelining#Ownership

    Basically this is what happens (super simplified example):

    #include 
    
    struct Foo{};
    
    class X
    {
        Foo *p_;
    public:
        X(Foo* p): p_(p) {}
        // we'd also need a copy ctor and copy assignment operator, ignored here
        ~X()
        {
            std::cout << "Releasing the memory...\n";
            delete p_;
        }
    };
    
    int main()
    {
        X x(new Foo()); // sinking, no memory leak
    }
    

    Live on Coliru

    I have to say that this is by far my least favourite style of software design. One can use templates and mixins to probably achieve similar things (read about policy based design), without pointers floating around with no clear ownership.

提交回复
热议问题