I have two classes that works like this:
typedef std::function<void (argument_types arguments)> my_func;
class A
{
public:
A(){};
...
void apply(argument_types arguments)
{
p_function(arguments)
v_function(arguments)
}
protected:
std::vector<T*> vec;
my_func p_function;
my_func v_function;
};
class B: public A
{
B(std::vector<T*> vec)
{
p_function = [this](argument_types arguments)
{
...
}
v_function = [this](argument_types arguments)
{
...
}
this->vec = vec;
}
}
I summarized with T* and argument_types arguments parts relative to other classes/structs declared elsewhere as i don’t think they’re relevant to the problem but i can go into more detail if needed.
my problem is that till i call apply the address of vec wich i printed using cout << &vec
the address is correctly read but, after p_function or v_function are called the same cout gives me a different output and obviously the data i want to access isn’t there anymore.
to be clear, i tried putting the cout right before calling p_function and on the first line of p_function but the address seems to change during function call.
in main i initialize class B
main()
{
...
B b(vec);
b.apply(arguments); // when calling this it gives error since it tries to access vec
// at a wrong address
}
What i expected is that the address of the declared std::vector to remain the same even after the function call.
I tried declaring the lambda with [&](...)
and [&,this]()
but neither changed the result
I initially tried to make sure that the memory where each and every T are declared doesn’t change no matter what but that too didn’t solve the problem.
One solution that kinda worked by avoiding the problem was by defining the functions as virtual and keeping the std::function as private only in the mother class, but i’d rather being able to implement them as std::function since i could need those in other child classes.
Marco Tambini is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.