I have two classes that work 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
{
public:
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, until I call apply()
the address of vec
(which I printed using cout << &vec
) is correct, but after p_function
or v_function
are called then 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 the 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 kind of worked to avoid 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 be 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.
4