【发布时间】:2011-11-20 22:12:32
【问题描述】:
更新 VS2012 修复了下面提到的错误,noncopyable 工作正常
这既是一个问题,也是一种提供信息/警告他人的方式,这样他们就不会像我一样落入同样的陷阱:似乎使用 noncopyable 基类(就像 boost 中的那个)在使用 MS 编译器时对导出的类没有影响。这是 a known bug 给 MS 但我怀疑有很多程序员知道它。可以想象,这会产生非常讨厌的错误,因为它允许编写甚至不应该编译的代码。示例(不可复制类的代码here:)
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() { 返回 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 放在不可复制的复制构造函数中也不会削减它,因为即使它没有被调用,编译器也会始终编译它。
【问题讨论】:
-
这种情况是仅返回一个对象还是您尝试过其他上下文?也许您的编译器在应用 NRVO 时没有检查可访问的复制构造函数(这是不合格的)。
-
@Luc Danton 将编辑并添加一些其他案例,不确定这是否是您对“其他上下文”的意思;确实可能是这里应用的一种相当残缺的 NRVO 形式(没有调用复制构造函数,但有析构函数)..
标签: c++ visual-studio visual-c++ dll noncopyable