小编Bal*_*n K的帖子

具有抑制移动构造/分配的类型如何仍被认为是可移动的?

struct copyable { // and movable
  copyable() = default;
  copyable(copyable const&) { /*...*/ };
  copyable& operator=(copyable const&) { /*...*/ return *this; }
};
Run Code Online (Sandbox Code Playgroud)

由于复制构造函数和复制赋值操作函数是显式定义的,因此它表示编译器不能隐式定义移动构造函数和移动赋值函数,因此不允许移动操作.

能告诉我上述理解是否正确吗?

c++ move-semantics c++11

26
推荐指数
1
解决办法
1630
查看次数

C++ 具有整数成员的对象的移动语义

#include<iostream>
#include<stdio.h>

using namespace std;
class Test
{    
   public:
       string n;
       Test():n("test") {}  
};

int main()
{
    Test t1;  
    std::cout<<"before move"<<"\n";
    std::cout<<"t1.n=" << t1.n<<"\n";
    Test t2=std::move(t1);

    std::cout<<"after move"<<"\n";
    std::cout<<"t1.n="<<t1.n<<"\n";
    std::cout<<"t2.n="<<t2.n<<"\n"; 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上述程序的输出产生以下结果

移动前 t1.n=测试 移动后 t1.n= t2.n=测试

了解到,将对象 t1 移动到 t2 后,t2.n 的值结果为空字符串

但相同的概念移动概念不适用于整数。

#include<iostream>
#include<stdio.h>

using namespace std;

class Test
{

    public:
        int n;
        Test():n(5) {}  

};

int main()
{
    Test t1;  
     std::cout<<"before move"<<"\n";
     std::cout<<"t1.n=" << t1.n<<"\n";
     Test t2=std::move(t1);

     std::cout<<"after move"<<"\n";
     std::cout<<"t1.n="<<t1.n<<"\n";
     std::cout<<"t2.n="<<t2.n<<"\n"; 

     return 0;
}
Run Code Online (Sandbox Code Playgroud)

上述程序的输出产生以下结果 …

c++ constructor move c++11 semantics

4
推荐指数
1
解决办法
2296
查看次数

标签 统计

c++ ×2

c++11 ×2

constructor ×1

move ×1

move-semantics ×1

semantics ×1