I'm experiencing a problem with a bounded function.
In short, I have a CheckState(int) std::function object, to which one of several different functions can be bound. At this point, I'm only using one test function.
The function object and the bound function are members of the same class.
It is bound during the creation of the object. CheckState = bind(CheckState_simple, this, _1);
I know that the object exists; I can see it is built correctly and works perfectly until it is inside the bound function. Suddenly, it's a corrupt object (looks uninitialized).
There is a vector of the owner class. I construct them like this:
1 2 3 4
vector<owner> list_of_owners;
for (ID = 0; ID < owner_count; ++ID) {
list_of_owners.emplace_back(basic_parameters);
}
The constructor simply initializes the member vars (including one reference) and binds the functions based on input parameters. I tried performing the binds afterwards manually (in case emplace_back has side effects I'm not aware of) to be sure they are being done with the correct object, but there was no change.
I'm not sure that is sufficient to check for copying, but I'm pretty confident there is nothing that can copy or move the object once its emplaced.
Okay, that previous line of thought made it obvious. Both vector::emplace_back and vector::push_back invalidate pointers of the objects already contained.
Ultimately just placing the Bind calls in a second loop, after all objects were constructed, was the obvious solution.
Thanks for the help, Peter87!
[edit]
To clarify, I said before "only this one seems to have problems", but that was because my breakpoints didn't catch the problem. The last object emplaced did have correct pointers (not invalidated due to following emplaces) and passed the checks just fine, and their behavior was much harder to spot when not looking directly at them.
So. Emplace/push_back invalidates pointers, including bound functions.
Ultimately just placing the Bind calls in a second loop, after all objects were constructed, was the obvious solution.
An alternative solution is to reserve enough space for all elements, before the loop starts, so that the calls to emplace_back don't cause the vector to reallocate.