编译器错误:仅需要复制省略号,但似乎需要移动构造函数(由编译器提供)

时间:2018-06-28 13:01:00

标签: c++ gcc visual-c++ rvo

尝试编译此代码会给“较新的”编译器带来编译器错误(我猜:该代码支持move构造函数)。类似于“尝试调用已删除的功能”。

事实证明,启用c ++ 17时使用gcc 8.1和clang 6.0.0进行编译(被认为是由于“保证复制省略”功能)是没有错误的。但是,也很清楚,使用MSVC 19.14(也启用了c ++ 17),即使它应该具有该功能(在19.13中出现),它也会失败。那么,这仅仅是MSVC的错误,是允许这样做,还是其他功能?

#include <string>
#include <iostream>
#include <sstream>


class A : public std::stringstream {
public:
  A(std::string str) : str_(str) {
  }
  //A(A&&);

  ~A() {
     std::cout << str_;
  }
  std::string str_;
};


A make_A() {
  return A("hello");
}

int test(int num) {
    A test = make_A();
}

“ A”类是复制删除(或RVO-返回值优化)的简单“利用”,并且它也不会调用自定义析构函数。

令人惊讶的是,在A的move构造函数的声明中进行注释,使代码既可以编译又可以链接。因此,看起来好像编译器首先“认为”它需要该功能-但后来弄清楚了复制省略是可能的。

这是预期的行为-无需调用。

在没有实现的情况下放入声明不再是一种好习惯。 我也在寻找更好的解决方案。

更新:该代码用于记录器类,该记录器类在调用时返回一个临时字符串流,该字符串流在销毁时将记录字符串缓冲区中的内容。记录器还具有一些内部信息,其中包括记录位置,严重性等的额外信息。

gcc 7.3的确切编译错误:

<source>: In function 'A make_A()':

<source>:21:19: error: use of deleted function 'A::A(const A&)'

   return A("hello");

                   ^

<source>:7:7: note: 'A::A(const A&)' is implicitly deleted because the default definition would be ill-formed:

 class A : public std::stringstream {

       ^

<source>:7:7: error: use of deleted function 'std::__cxx11::basic_stringstream<_CharT, _Traits,
_Alloc>::basic_stringstream(const std::__cxx11::basic_stringstream<_CharT, _Traits, _Alloc>&) [with
_CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'

In file included from <source>:4:0:

/opt/compiler-explorer/gcc-7.3.0/include/c++/7.3.0/sstream:734:7: note: declared here

       basic_stringstream(const basic_stringstream&) = delete;

       ^~~~~~~~~~~~~~~~~~

<source>:7:7: error: use of deleted function 'std::basic_ios<_CharT,
_Traits>::basic_ios(const std::basic_ios<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]'

 class A : public std::stringstream {

       ^

In file included from /opt/compiler-explorer/gcc-7.3.0/include/c++/7.3.0/ios:44:0,

                 from /opt/compiler-explorer/gcc-7.3.0/include/c++/7.3.0/ostream:38,

                 from /opt/compiler-explorer/gcc-7.3.0/include/c++/7.3.0/iostream:39,

                 from <source>:3:

/opt/compiler-explorer/gcc-7.3.0/include/c++/7.3.0/bits/basic_ios.h:475:7: note: declared here

       basic_ios(const basic_ios&) = delete;

       ^~~~~~~~~

<source>: In function 'int test(int)':

<source>:25:21: error: use of deleted function 'A::A(const A&)'

     A test = make_A();

                     ^

Compiler returned: 1

1 个答案:

答案 0 :(得分:0)

即使使用最新发布的MSVC版本(VS17版本15.7.6),“保证复制删除”的MSVC状态似乎也存在问题。

例如,请参见此勾选: https://developercommunity.visualstudio.com/content/problem/217997/guaranteed-copy-elision-incomplete-in-1562.html

更新:MS已修复最新VS17版本15.8.1的问题