C++ – Where is the dynamic memory associated with std::bind

cc++11

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:

std::function foo(std::bind(this, "yellow"));

The std::function will copy the result of std::bind to the heap. When the std::function is destroyed it will automatically release the memory for the copy.

If you did something like:

vector_of_function.push_back(std::function(std::bind(this, "yellow")));

The std::bind will be copied into heap allocated by the std::function and the std::function will be copied into heap allocated by the std::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 must delete. Since the standard library is responsible for new the copies in these cases, the standard library will delete them.