Memory Management

Hi all,

I have a question about how the pointers on OpenFHE objects work. So as far as I understood it, an object of classes like Ciphertext<DCRTPoly> or Cryptocontext<DCRTPoly> are really (shared?) pointers to implemented objects. This means, that if I call an object of that kind by value and not by reference, it does not use a the huge amount of memory a large ciphertext might use. Now my question is how for example the EvalAdd or EvalMult methods handle that. So if I have the code snippet

Ciphertext<DCRTPoly> calculateMean(Ciphertext<DCRTPoly> input, CryptoContext<DCRTPoly> context, unsigned int N) {
    input = context->EvalSum(input, N);
    input = context->EvalMult(input, (double) 1./N);

    return input;
}

does the EvalSumm method then allocate memory to the resulting object and keep it till the next assignment of input variable, or when is that memory freed?

Thanks in advance and cheers

PS: Sorry if this is more of a C++ question than an OpenFHE question :slight_smile:

Good day.

Your intuition is correct in that the way that you are using the variable input in your code will cause the contents of the local result object to be newly allocated within the Eval*() operations, and assigned to the shared pointer input each time the assignment operator is used.

Further, this code will act as one would expect when passing by value, in that the caller’s version of input will remain unchanged when calculateMean() returns.

When passing by value in this manner, the reference count of the shared pointer is incremented when it is copied, in order to be placed on the stack. When making the first assignment, that reference count will be decremented when the new version of input is created by the assignment operator.

While this is mostly a C++ question, it is informative to the community at large. We are happy to help foster understanding of our use of modern C++ features within OpenFHE. If you have further questions, please feel free to ask them.

Regards,

Jack Bates
Duality

Thanks a lot for the answer! So this means that it is not really practicable to call OpenFHE objects with const <objectname>& in order to save memory, if a copy of the variable doesn’t need to be changed within a function or method, since it only copies the size of the pointer variable to memory?