I am a little confused about what happens when I copy functors and/or initializers. In the following code I thought I would copy/move the objects all the time but regardsless it Segfaults. I seem to be doing something wrong but haven’t figured out yet, what my wrong asumptions are.
Strangely at cppreference.com I could not find copy or move constructor for initializer_list so I wonder what actually happens in these cases.
#include <string>
#include <vector>
#include <functional>
#include <iostream>
std::initializer_list<std::function<std::string()>> getInitializer() {
return {
[]() -> std::string {
return "If";
}
};
}
int main() {
std::function<int(std::string)> func;
{
auto init = getInitializer();
func = [init](std::string text) -> int {
std::vector<std::function<std::string()>> vec(init);
for( auto& el : vec ) {
std::cout << el();
}
std::cout << text << std::endl;
return 5;
};
}
return func(" you see this - the world is all right!");
}
I don’t have much experience with
initializer_lists, but the standard seems to suggest the implementation of aninitializer_listis as if its a pair of pointers to an array. The list atgetInitializerhas automatic lifetime, and so does the array that backs it. You end up returning a pair of pointers to an array that no longer exists.The relevant sections of the standard are 8.5.4 [decl.init.list] items 5 and 6:
So for your particular case, the implementation would be roughly equivalent to this: