I have a function that takes a vector of objects that store lambdas as class members. The class also has a static function that takes a vector of these objects and creates a lambda that sums the values of each object's lambda. To test the builder function I've created a test fixture struct with stores a vector of objects. When I use the builder function with the vector stored in the struct I get weird return values from the constructed lambda; when I create a vector of objects outside of a struct the return values are fine. Here is an example code that reproduces the situation:
#include <iostream>
#include <vector>
class LambdaBuilder {
double m_;
double b_;
protected:
// lambda member
std::function<double(double)> lambda_function
= [this](double x){return m_*x+b_;};
public:
// sums the lambda member in a vector of LambdaBuilders
LambdaBuilder(double m, double b) : m_(m), b_(b){};
static std::function<double(double)>
buildFunction(const std::vector<LambdaBuilder> &lambdas){
auto ret = [&lambdas](double x){
double val = 0;
for (auto & lam : lambdas)
val += lam.lambda_function(x);
return val;
};
return ret;
}
};
// constructs and stores a vector of LambdaBuilders
struct Fixture{
std::vector<LambdaBuilder> lambdas;
Fixture(){
LambdaBuilder lambda_0(1,2);
lambdas.push_back(lambda_0);
}
};
int main(int argc, const char * argv[])
{
Fixture fixture;
auto built_function_fixture = LambdaBuilder::buildFunction(fixture.lambdas);
LambdaBuilder lambda_0(1,2);
std::vector<LambdaBuilder> lambdas = {lambda_0};
auto built_function_vector = LambdaBuilder::buildFunction(lambdas);
std::cout << "Function from Feature fixture: "
<< built_function_fixture(5) << std::endl;
std::cout << "Function from Feature vector: "
<< built_function_vector(5) << std::endl;
std::cout << "Should be: " << 1*5 + 2 << std::endl;
return 0;
}
The code outputs
Function from Feature struct: 3.47661e-309
Function from Feature vector: 7
Should be: 7
Program ended with exit code: 0
I'm a little new to C++11 and I'm not quite sure what is causing the weird results from the fixture.