The problem is that since you can use std:bind in a loop with an arbitrary number of iterations, the storage cannot be inline. It doesn't appear to be on the heap, since it doesn't appear to generate memory leaks. It seems, then, that it must be on the stack – SOME stack. I have an application which could easily do hundreds of thousands of these binds setting up calls to a threader. Since the caller could presumably go out of scope while the threader is still working, and since the threader needs the bind until it executes the job, that information must be stored SOMEWHERE. Where is it, and how do I clean it up when the binds have served their purpose?
Example:
std::function<void()> *Jobs;
Jobs = new std::function<void()> Jobs[nJobs];
for (i=0; i<nJobs; ++i)
{
Jobs[i] = std::bind (funtion, args, ...);
}
ThreadPool->QueueJobs (Jobs, nJobs); // store POINTERS to jobs
ThreadPool->WaitForCompletion();
delete Jobs;
Does this look like it will work?
Best Answer
The return value of std::bind is entirely on the stack. If you just called std::bind and did nothing else with it it would be on the stack and then disappear when it went out of scope.
In order to do anything useful with the result of std::bind you must have explicitly or implicitly made a copy of it, probably to some place in the heap.
For example, if you did this:
The
std::function
will copy the result ofstd::bind
to the heap. When thestd::function
is destroyed it will automatically release the memory for the copy.If you did something like:
The
std::bind
will be copied into heap allocated by thestd::function
and thestd::function
will be copied into heap allocated by thestd::vector
. But in neither case do you need to worry about it because the vector and function will take care of deallocation when they are destroyed.The rule in C++ is that whatever you
new
you mustdelete
. Since the standard library is responsible fornew
the copies in these cases, the standard library willdelete
them.