使用std :: bind时出现运行时错误

时间:2016-03-11 11:08:06

标签: c++ c++11 visual-studio-2013 stdbind

以下代码使用Xcode 6.3.2在OS X上成功编译并运行。但是,使用VS2013在Windows上运行时会崩溃。

#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;
}

崩溃的原因是properties中的第一个元素似乎已损坏。当我检查内存时,我看到了:

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> > > *

如果我直接调用std::bind替换validate作为properties中的第一个元素,则代码会成功执行。

有人可以解释我做错了什么。

1 个答案:

答案 0 :(得分:0)

我注意到Paul R上面的评论他使用VC2013成功运行了代码,所以我更新了我的Visual Studio 2013副本(更新5),现在代码运行正常。所以我猜它编译器错误。