当我尝试声明一个类变量时,我在 Visual Studio 2015 中遇到编译错误,而该类使用 PIMPL 模式。
Foo.h:
#pragma once
class Foo
{
public:
Foo(const std::wstring& str,
const std::vector<std::wstring>& items);
~Foo();
private:
struct Impl;
std::unique_ptr<Impl> pimpl;
};
Foo.cpp:
#include "stdafx.h"
#include "Foo.h"
struct Foo::Impl
{
public:
Impl(const std::wstring& str,
const std::vector<std::wstring>& items);
std::wstring str_;
std::vector<std::wstring> items_;
};
Foo::Foo(const std::wstring& str,
const std::vector<std::wstring>& items)
: pimpl(std::make_unique<Impl>(str, items))
{
}
Foo::~Foo() = default;
Foo::Impl::Impl(const std::wstring& str,
const std::vector<std::wstring>& items)
: str_(str),
items_(items)
{
}
如果我使用传统语法声明类型为 Foo
的变量,它可以正常编译:
Foo f(L"Hello", std::vector<std::wstring>());
但是,如果我使用 auto
声明它,则会出现编译错误:
auto f2 = Foo { L"Goodbye", std::vector<std::wstring>() };
error C2280: 'Foo::Foo(const Foo &)': attempting to reference a deleted function
note: compiler has generated 'Foo::Foo' here
我知道应该删除 Foo
的复制构造函数,因为 unique_ptr
无法复制。然而,我的理解是,当以这种方式声明变量时,结果要么被 move 到变量中,要么直接将值设置到变量中。
第二行在使用 Visual Studio 2013 时编译正常。我检查了 Visual Studio 2015 中的重大更改,但我没有看到任何可以表明为什么开始失败的内容。
我是不是做错了什么,或者这个语法不能用于不可复制的类型?
最佳答案
move 构造函数未隐式声明,因为您有一个用户声明的析构函数(参见 [class.copy]/(9.4) )。但是,显然删除了复制构造函数,因为无法复制 unique_ptr
。
您可以将 move 构造函数显式声明为默认。
关于c++ - 为什么我不能使用 auto 声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858457/