更新以下提到的错误已在 VS2012 中修复,并按noncopyable
预期工作
这既是一个问题,也是一种提供信息/警告他人的方法,这样他们就不会像我一样落入同一个陷阱:似乎使用noncopyable
基类(如 boost 中的基类)在使用时对导出的类没有影响MS 编译器。这是MS 的一个已知错误,但我怀疑有很多程序员知道它。可以想象,这会产生非常讨厌的错误,因为它允许编写甚至不应该编译的代码。示例(此处为不可复制类的代码:)
dll项目中的典型头文件,编译/D EXPORT_IT
:
#ifdef EXPORT_IT
#define mydll __declspec( dllexport )
#else
#define mydll __declspec( dllimport )
#endif
class mydll CantCopyMe : private noncopyable
{
public:
CantCopyMe();
~CantCopyMe();
};
mydll CantCopyMe MakeIt();
源文件:
#include <iostream>
CantCopyMe::CantCopyMe()
{
std::cout << "constructor" << std::endl;
}
CantCopyMe::~CantCopyMe()
{
std::cout << "destructor" << std::endl;
}
CantCopyMe MakeIt()
{
CantCopyMe x;
return x; //oops... this sould not compile nor link but it does
}
应用程序:
int main()
{
CantCopyMe x( MakeIt() );
}
输出:
constructor
destructor
destructor
1个构造函数,2个析构函数被调用。想象一下当类有效地包含资源时的问题。
编辑 可以编译但不应编译的用例:
CantCopyMe MakeIt()
{
CantCopyMe x;
return x;
}
void DoIt( CantCopyMe x )
{
x.Foo();
}
void SomeFun()
{
CantCopyMe x;
DoIt( x );
}
其他情况:CantCopyMe MakeIt() { return CantCopyMe(); //致命错误C1001 }
CantCopyMe GenerateIt()
{
CantCopyMe x;
return x;
}
CantCopyMe MakeIt()
{
return GenerateIt(); //fatal error C1001
}
CantCopyMe MakeIt()
{
CantCopyMe x;
return CantCopyMe( x ); //fatal error C1001 + cl crashes
}
void DoSomething()
{
CantCopyMe x;
CantCopyMe y = x; //fatal error C1001 + cl crashes
}
问题:
知识库文章提到了即将发布的版本中的修复。任何人都可以检查这是否已经在 VS2010 中修复(或者可能使用 Visual Studio 11 预览版)?
是否有任何解决方法来触发任何类型的错误?我尝试(ab)使用编写触发内部编译器错误的事实,
return CantCopyMe()
但是,我找不到一种方法来仅在编译上述函数时有条件地触发它MakeIt
。将 static_assert 放在不可复制的复制构造函数中也不会削减它,因为即使它没有被调用,编译器也会始终编译它。