Search code examples
c++c++11visual-studio-2013reference-wrapper

std::reference_wrapper on MS Visual Studio 2013


I try to compile some code which is very similar to:

#include <string>
#include <unordered_map>

class A{
};

int main(int argc, char* argv[]){
  std::unordered_map<std::string, std::reference_wrapper<const A>> stringToRef;
  A a;
  const A& b = a;
  stringToRef.insert(std::make_pair("Test", b));
  return 0;
}

But can't figure out, why it's not compiling. I'm pretty sure, that the same code compiled fine on MS Visual Studio 2012 - but on Visual Studio 2013, it reports the following compilation error:

error C2280: std::reference_wrapper<const A>::reference_wrapper(_Ty &&): attempting to reference a deleted function

I tried to add copy, move, assignment operators to my class - but couldn't get rid of this error. How can I find out exactly, which deleted function this error refers to?


Solution

  • You want to store a std::reference_wrapper<const A>, so you can use [std::cref][1] to get that directly from a:

    #include <functional>
    #include <string>
    #include <unordered_map>
    #include <utility>
    
    class A{
    };
    
    int main(int argc, char* argv []){
      std::unordered_map<std::string, std::reference_wrapper<const A>> stringToRef;
      A a;
      stringToRef.insert(std::make_pair("Test", std::cref(a)));
      return 0;
    }
    

    This works with GCC/Clang+libstdc++, Clang+libc++, and MSVS 2013 (tested locally).