2016-03-11 41 views
1

以下代碼使用Xcode 6.3.2在OS X上編譯併成功運行。但是,它在使用VS2013的Windows上運行時會崩潰。使用std :: bind時出現運行時錯誤

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

如果我作爲在properties那麼代碼執行成功的第一要素直接調用validate取代std::bind

有人可以解釋我做錯了什麼。

+0

我已經使用VC2013編譯了您的代碼,但我無法重現該錯誤。在閱讀代碼時我也找不到錯誤。這真的是你正在運行的確切代碼嗎? –

+0

g ++和clang ++會用'validate'報告錯誤 - 第三個參數必須是const。編譯器報告了這樣的錯誤嗎?如果這個問題得到解決,一切都按預期工作。 – karastojko

+0

@PaulR。這正是我跑的代碼。 – ksl

回答

0

我注意到上面Paul R的評論,他成功地使用VC2013運行代碼,所以我更新了Visual Studio 2013(更新5)的副本,現在代碼運行正常。所以我猜想的一個編譯器bug。

相關問題