The following code compiles and runs successfully on OS X using Xcode 6.3.2. However, it crashes when run on Windows using VS2013.
#include <vector>
#include <string>
#include <memory>
#include <functional>
#include <iostream>
void validate(const std::string& name,
int value,
std::vector<std::string>& values)
{
std::cout << "name: " << name << " value: " << value << "\n";
}
struct Property
{
public:
Property(const std::string& name,
const std::function<void(const std::string&, int)>& validationFunction) :
m_name(name),
m_validationFunction(validationFunction)
{
}
const std::string m_name;
const std::function<void(const std::string&, int)> m_validationFunction;
};
const std::vector<std::shared_ptr<Property>> properties
{
{
std::make_shared<Property>("identifier1",
[](const std::string& name, int value)
{
validate(name, value, std::vector<std::string>{"foo"});
})
},
{
std::make_shared<Property>("identifier2",
std::bind(validate,
std::placeholders::_1,
std::placeholders::_2,
std::vector<std::string>{"bar"}))
}
};
int main()
{
properties[0]->m_validationFunction(properties[0]->m_name, 4);
properties[1]->m_validationFunction(properties[1]->m_name, 5);
return 0;
}
The reason for the crash is that the first element in properties
appears to be corrupt. When I inspect the memory I see this:
properties { size=2 } std::vector<std::shared_ptr<Property>,std::allocator<std::shared_ptr<Property> > >
[size] 2 int
[capacity] 2 int
[0] shared_ptr {m_name=<Error reading characters of string.> m_validationFunction={...} } [4277075694 strong refs, 4277075693 weak refs] [{_Uses=4277075694 _Weaks=4277075694 }] std::shared_ptr<Property>
[1] shared_ptr {m_name="identifier2" m_validationFunction=bind(0x011315a5 {schema-init.exe!validate(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,int,class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > &)}, (_1, _2, { size=1 })) } [1 strong ref] [make_shared] std::shared_ptr<Property>
[Raw View] 0x0115295c {schema-init.exe!std::vector<std::shared_ptr<Property>,std::allocator<std::shared_ptr<Property> > > properties} {...} std::vector<std::shared_ptr<Property>,std::allocator<std::shared_ptr<Property> > > *
If I replace std::bind
with a direct call to validate
as for the first element in properties
then the code executes successfully.
Can someone explain what I'm doing wrong.