Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
4.75/5 (4 votes)
See more:
Hi, All

Recently I try to use std::function and Lambda expression to simply my code.
However there are some weird problems.

C++
#include <cstdio>
#include <vector>
#include <functional>

int main(int argc, char *argv[])
{
	std::function<bool (int)> arr[]={
		[&](int n)->bool {
			std::wstring y;

			printf("function 0, %d\n", n);
			return false;
		},
   
		[&](int n)->bool {
			std::wstring y;

			printf("function 1, %d\n", n);
			return false;
		}
	};
  
	arr[1](100);
	return 0;
}


Above code can be compiled by VS2010, but crush during run-time.
I found the internal pointer _Impl of function template holds invalid address.

If I define an array in lambda functions, the program crashes at runtime with C1001.

The following code, does not crash, only difference, used int x[100] instead of std::wstring y:
C++
#include <cstdio>
#include <vector>
#include <functional>

int main(int argc, char *argv[])
{
	std::function<bool (int)> arr[]={
		[&](int n)->bool {
			int x[100]={0};

			printf("function 0, %d\n", n);
			return false;
		},
   
		[&](int n)->bool {
			int x[100]={0};

			printf("function 1, %d\n", n);
			return false;
		}
	};
  
	arr[1](100);
	return 0;
}


Any advice will be appreciated.
Posted
Updated 2-Jan-13 5:20am
v3
Comments
armagedescu 2-Jan-13 11:14am    
I think the destructor of std::wstring does that. The problems appears with constructing/destructing and new/delete operators. Seems like arrays of std::function are not supported, or not well supported yet.
Sergey Alexandrovich Kryukov 2-Jan-13 12:16pm    
Crash? I believe there is not crash, more likely, this is unhandled exception. Could you simply execute this under the debugger and comment in what line the exception was thrown?
—SA
armagedescu 3-Jan-13 5:25am    
Is not unhandled exception. It is Access Violation while calling of a member function by invalid pointer.
Sergey Alexandrovich Kryukov 3-Jan-13 11:27am    
Thank you; Maximilien already told me about compiler crash. Too bad.
—SA
armagedescu 3-Jan-13 12:07pm    
So, as I see, there are two problems.
1. Program can't be compiled because compiler crashes.
2. If compiler can compile the program, then the program crashes at runtime.
In both cases seems to be like bugs in VisualStudio 2010 and above.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900