Reputation: 1175
There are lots of places that I got code like this:
some_function_signature()
{
T a;
T b = f1(a);
T c = f2(b);
T d = f3(c);
...
}
As you can see, in such a function, a
is passed to f1()
to produce b
, then b
passed to f2()
to produce c
, and so on. These variables are not going to be used after the function call (f1,f2,f3
...). And they hold large memory (e.g. T
is big image data). The problem here is that within this function, the accumulated memory consumption can be large and I'd like to reduce that. Waiting for the destructor of T to release the memory will make the peak memory usage of some_function_signature()
very big.
I can do something like this to free the memory after use:
some_function_signature()
{
T a;
T b = f1(a); a.free();
T c = f2(b); b.free();
T d = f3(c); c.free();
...
}
I wonder if I can make this process automatic and more elegant.For example, a scoped memory management process or using sort of reference counting, but I just don't know how to best apply these methods here.
Upvotes: 1
Views: 129
Reputation: 26810
You can try something like this:
T d;
{
T c;
{
T b;
{
T a;
b = f1(a);
} //a goes out of scope and is destroyed here
c = f1(b);
} //b goes out of scope and is destroyed here
d = f3(c);
}//c goes out of scope and is destroyed here
Upvotes: 0
Reputation: 180303
This looks like a case for move semantics. Make sure that T
and f1/2/3
support move semantics, and change the example to
some_function_signature()
{
T a;
T b = f1(std::move(a));
T c = f2(std::move(b));
T d = f3(std::move(c));
...
}
This would allow T f1(T&& t)
to recycle the moved-in image.
Upvotes: 6