Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler error when exporting class

I am using Visual Studio 2013 and am having a strange issue. When I export a class it throws "attempting to reference a deleted function" error. However when the class is not exported it behaves correctly.

Let me give an example...

class Foo
{

};

      // note the export
class __declspec(dllexport) Bar
{
    // the following line throws the error
    std::unordered_map<std::string, std::unique_ptr<Foo>> map;
};

Now if I remove the export so it looks like the following all works as expected.

class Foo
{

};

// note I removed the export
class Bar
{
    // the following line now compiles without any issues
    std::unordered_map<std::string, std::unique_ptr<Foo>> map;
};

Now, is this a compiler bug or something else that I am obviously missing? Just for reference, the above code works fine with GCC or Clang.

Error   2   error C2280: 'std::unique_ptr<Foo,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function    c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0 592 
like image 394
Zachariah Brown Avatar asked Jul 06 '14 19:07

Zachariah Brown


1 Answers

When exporting a class from a dll, the compiler explicitly generates all the special member methods (copy constructor etc. that would in this case have otherwise been left undeclared ). As you see, the generated copy constructor then generates an invalid copy on the unique pointer; thus the error.

I don't think this is just a bug, I think it is most likely part of an unsupported scenario.

You could try to explicitly delete in the Bar class copy constructor and check if the compiler accepts it.

like image 191
Niall Avatar answered Oct 21 '22 10:10

Niall