c++ - 为什么我不能使用 auto 声明变量?

标签 c++ c++11 visual-c++ visual-studio-2015 move-semantics

当我尝试声明一个类变量时,我在 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/

相关文章:

c++ - VSCode c++ task.json包含路径和库

c++ - 什么是RMI的C版本

c++ - 如何将简单的 API 添加到我的 C++ 应用程序以供 LabView 访问?

c++ - 为什么我可以将字符串文字分配给 char* 指针

c++ - 如何检测使用 GetOpenFileName 创建的文件对话框?

c++ - 检索字符并以相反顺序返回的递归函数c++

c++ - 强制评估 constexpr 静态成员

c++ - add_lvalue_reference_t<T> 和 T& 之间的区别

c++11 - 类型在可变参数模板参数包中的位置

c++ - 如何在 C++ 中判断应用程序在何处运行