在写这个问题的答案时,我遇到了一个有趣的情况 - 这个问题演示了一个人想要将一个类放在STL容器中但由于缺少复制构造函数/移动构造函数/赋值运算符而无法执行此操作的情况.在这种特殊情况下,错误由触发std::vector::resize.我做了一个快速片段作为解决方案,并看到另一个答案,提供了一个移动构造函数,而不是像我一样提供赋值运算符和复制构造函数.什么是有趣的,另一个答案没有在VS 2012中编译,而clang/gcc对这两种方法都很满意.
第一:
// Clang and gcc are happy with this one, VS 2012 is not
#include <memory>
#include <vector>
class FooImpl {};
class Foo
{
std::unique_ptr<FooImpl> myImpl;
public:
Foo( Foo&& f ) : myImpl( std::move( f.myImpl ) ) {}
Foo(){}
~Foo(){}
};
int main() {
std::vector<Foo> testVec;
testVec.resize(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第二:
// Clang/gcc/VS2012 are all happy with this
#include <memory>
#include <vector>
using namespace std;
class FooImpl {};
class Foo
{
unique_ptr<FooImpl> …Run Code Online (Sandbox Code Playgroud)