相关疑难解决方法(0)

为什么当我不移动任何东西时,clang会抱怨删除的移动?

前提:

#include <iostream>
using namespace std;

class ABC {
 public:

   ABC() {
     cout << "Default constructor ..\n";
   }

   ABC(const ABC& a) {
     cout << "In copy constrcutor ..\n";
   }
   ABC(ABC&& aa) = delete;
};

int main(int argc, char* argv[]) {
  ABC b{ABC{}};
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

用GCC vs Clang编译它

Clang - Apple LLVM version 8.1.0 (clang-802.0.42)

Gcc - 5.4.0 ubuntu

观察 Clang抱怨删除了Move构造函数.

Gcc完全不抱怨.并将正确输出.

问题为什么?

对于gcc,我知道如果你只是初始化lvalue和rvalue,它会优化并且实际上不会调用复制构造函数并将临时值复制到左值.

为什么Clang有所不同?我认为(不确定,因此问题)这是在C++标准中,哪一个偏离(或不)?或者我做错了什么.

编译命令:g++ --std=c++11 -O3 file.cpp

为了更多的乐趣,删除花括号,并添加括号;)

ABC b{ABC{}};to,ABC b(ABC());与此问题无关. …

c++ clang gcc-warning move-constructor move-semantics

3
推荐指数
1
解决办法
194
查看次数

为什么编译器需要复制构造函数,需要并且移动一个并且不使用它们中的任何一个?

我已经尝试过问这个问题,但我还不够清楚.所以这是另一个尝试.我对我的英语很抱歉;)

我们来看看代码:

#include <iostream>
#include <memory>
using namespace std;

struct A {
    unique_ptr<int> ref;

    void printRef() {
        if (ref.get())
            cout<<"i="<<*ref<<endl;
        else
            cout<<"i=NULL"<<endl;
    }

    A(const int i) : ref(new int(i)) { 
        cout<<"Constructor with ";
        printRef();
    }
    ~A() {
        cout<<"Destructor with";
        printRef();
    }
};

int main()
{
    A a[2] = { 0, 1 };
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

它无法编译,因为unique_ptr已删除复制构造函数.
奥利?
这个类有一个隐含的移动构造函数,因为unique_ptr有一个.

我们来做一个测试:

#include <iostream>
#include <memory>
using namespace std;

struct A {
    unique_ptr<int> ref;

    void printRef() {
        if (ref.get())
            cout<<"i="<<*ref<<endl;
        else …
Run Code Online (Sandbox Code Playgroud)

c++ constructor copy-constructor move-constructor c++11

2
推荐指数
1
解决办法
223
查看次数