Reputation: 42716
I just find something that couldn't understand. I think it should be related to the functions stack and some undefined behavior.
Let's say I have a function factory template (silly one):
template <unsigned int N=10>
std::function<int&&(const int& n)> build_add_function() {
return [](const int& n) -> int&& {std::move(n+N);};
}
As you can see, it lacks the return statement on a non-void function, hence the compiler throw me a warning... The strange thing is that it works "as expected"
int main() {
auto foo = build_add_function();
std::cout << foo(10);
}
main output: 20
Of course, to fix the code, I added the return
statement and it gives me a segmentation fault
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
I have some misconception of what I'm doing for sure, but I just can not get it around. Would someone explain to me what is happening here?
I'm using gcc
version 8.0.1
EDIT: Just tested on gcc 4.8.1
and worked as expected with the return statement and no compilation errors.
Is it a compiler stuff?
Upvotes: 3
Views: 544
Reputation: 172934
Both the cases are undefined behavior.
The behavior of non-void function lacks return
statement is undefined (except for main()
), that means anything is possible. Even you might get the "correct" result you shouldn't rely on it.
When you added the return
statement like return std::move(n+N);
, you're trying to return a reference to temporary, which is always dangled, and dereference on it leads to UB too.
Upvotes: 6