相关疑难解决方法(0)

什么是C++中的复制/移动构造函数选择规则?什么时候发生移动复制后备?

第一个例子:

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

struct A {
    unique_ptr<int> ref;
    A(const A&) = delete;
    A(A&&) = default;
    A(const int i) : ref(new int(i)) { }
    ~A() = default;
};

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

它完美地运作.所以这里使用了MOVE构造函数.

让我们删除移动构造函数并添加一个副本:

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

struct A {
    unique_ptr<int> ref;
    A(const A&a) 
        : ref( a.ref.get() ? new int(*a.ref) : nullptr )
    {  }
    A(A&&) = delete;
    A(const int i) : ref(new …
Run Code Online (Sandbox Code Playgroud)

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

15
推荐指数
2
解决办法
1008
查看次数

即使不使用移动构造函数也是必需的.为什么?

为什么?!为什么C++要求类可以移动,即使它没有被使用!例如:

#include <iostream>
using namespace std;

struct A {
    const int idx;
    //   It could not be compileld if I comment out the next line and uncomment
    // the line after the next but the moving constructor is NOT called anyway!
    A(A&& a) : idx(a.idx) { cout<<"Moving constructor with idx="<<idx<<endl; }
   //  A(A&& a) = delete;
    A(const int i) : idx(i) { cout<<"Constructor with idx="<<i<<endl; }
    ~A() { cout<<"Destructor with idx="<<idx<<endl; }
};

int main()
{
    A a[2] = { …
Run Code Online (Sandbox Code Playgroud)

c++ std c++11 c++14

4
推荐指数
2
解决办法
445
查看次数

标签 统计

c++ ×2

c++11 ×2

c++14 ×1

copy-constructor ×1

move-constructor ×1

std ×1