小编Per*_*ter的帖子

为什么以下代码不会导致移动对象而不是复制?

#include <iostream>
#include <time.h>

class A
{
public:
   A() { std::cout << "a ctor\n"; }
   A(const A&) { std::cout << "a copy ctor\n"; }
   A(A&&) { std::cout << "a move ctor\n"; }
};

A f(int i)
{
   A a1;
   return i != 0 ? a1 : A{};
}

int main()
{
   srand(time(0));
   f(rand());
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

演员

复印机

我预计A1F()将被移动不会被复制。如果我稍微改变f(),它就不再是一个副本而是一个移动:

A f(int i)
{
   A a1;
   if (i != 0)
   {
      return a1;
   } …
Run Code Online (Sandbox Code Playgroud)

c++ move-semantics c++11

6
推荐指数
1
解决办法
144
查看次数

标签 统计

c++ ×1

c++11 ×1

move-semantics ×1