【发布时间】:2015-03-23 04:54:30
【问题描述】:
以下代码在Visual Studio 2013下会崩溃
我想知道为什么:在这种情况下编写移动构造函数的正确方法是什么? 删除移动构造函数解决了这个问题。 是VC++的bug还是这段代码错了?
移动构造函数的默认定义有什么不同,使这段代码不会崩溃,而我自己的定义会崩溃?
#include <memory>
#include <vector>
class A
{};
class Foo
{
public:
Foo(std::unique_ptr<A> ref) : mRef(std::move(ref)) {}
Foo(Foo&& other) : mRef(std::move(other.mRef)) {}
Foo(const Foo& other) {}
Foo& operator=(const Foo& other) { return *this; }
protected:
std::unique_ptr<A> mRef;
};
int main(int argc, char *argv[])
{
std::vector<Foo>({ Foo(std::make_unique<A>()), Foo(std::make_unique<A>()) });
// Crash : Debug Assertion Failed !
// Expression : _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
}
这可能与此有关,对吧?
Double delete in initializer_list vs 2013
这里是实际的代码,带有充实的复制构造函数和赋值,但错误是完全一样的
class A
{
public:
std::unique_ptr<A> clone() { return std::make_unique<A>(*this); }
};
class Foo
{
public:
Foo(std::unique_ptr<A> ref) : mRef(std::move(ref)) {}
Foo(Foo&& other) : mRef(std::move(other.mRef)) {}
Foo(const Foo& other) : mRef(other.mRef->clone()) {}
Foo& operator=(const Foo& other) { mRef = other.mRef->clone(); return *this; }
protected:
std::unique_ptr<A> mRef;
};
【问题讨论】:
-
MCVE?您需要包含
<vector>。 -
适用于 clang++ 和 g++4.9
-
我最好的猜测是这是一个在 VS-2015 中解决的错误,也许看到我在最后添加的链接?
-
可能与您当前的问题无关,但无论如何:您的 copy 构造函数和赋值运算符实际上并未复制。
标签: c++ visual-c++ c++14 unique-ptr move-constructor