微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在函数参数列表中构造对象时未调用移动构造函数

如何解决在函数参数列表中构造对象时未调用移动构造函数

编辑:我对为什么 printSize(MovableArray(30))调用移动构造函数感到特别困惑。

我有以下代码来测试 C++ 中的移动构造函数MovableArray 类是使用复制和交换习语设计的。我想测试移动语义是否真的有效。

但是,main 函数中带有 printSize(MovableArray(30)) 的表达式似乎没有调用移动构造函数

通过告诉编译器不要执行复制省略,我设法获得了带有 40 调用移动构造函数的行。所以我猜测 30 调用背后的原因也是由于编译器优化。但是,我没有从 clang 文档中找到标志。

谁能指出原因?谢谢。

#include <algorithm>
#include <iostream>
#include <utility>

class MovableArray
{
public:
  MovableArray()
    : size_{ 0 },data_{ nullptr }
  {}
  explicit MovableArray(int size) // ctor
    : size_(size),data_{ new int[size]() } {};
  ~MovableArray() // dtor
  {
    delete[] data_;
    std::cout << "deleted array of size " << size_ << std::endl;
  };
  MovableArray(const MovableArray& other) // copy constructor
    : size_{ other.size_ },data_{ new int[size_]() }
  {
    std::copy(other.data_,other.data_ + other.size_,this->data_);
    std::cout << "Array of size " << size_ << " is copied\n";
  }

  MovableArray(MovableArray&& other) // move constructor
    : MovableArray()
  {
    swap(*this,other);
    std::cout << "Array of size " << size_ << " is moved\n";
  }

  friend void swap(MovableArray& a,MovableArray& b) throw()
  {
    using std::swap;
    swap(a.data_,b.data_);
    swap(a.size_,b.size_);
  }
  int size() const { return this->size_; }
  int operator[](int i) const { return data_[i]; }
  int& operator[](int i) { return data_[i]; }

private:
  MovableArray& operator=(const MovableArray& rhs); // copy operator
  MovableArray& operator=(MovableArray&& rhs);      // move operator
  // MovableArray& operator=(MovableArray rhs);        // both
  int size_;
  int* data_;
};

void
printSize(MovableArray a)
{
  /* for (int i = 0; i < a.size(); ++i) */
  /*   std::cout << a[i] << "\t"; */
  /* std::cout << std::endl; */

  std::cout << "Size of array is " << a.size() << std::endl;
}

MovableArray
createArray(int size)
{
  auto ret = MovableArray(size);
  return ret;
}

int
main()
{
  MovableArray a{ 20 };
  // copied
  printSize(a);
  // explicitly moved
  printSize(std::move(a));
  // implicitly moved,why not working? Todo
  printSize(MovableArray(30));
  // implicitly moved
  // need to be compile with option 
  //     -fno-elide-constructors
  printSize(createArray(40));
}

我得到的输出

Array of size 20 is copied
Size of array is 20
deleted array of size 20
Array of size 20 is moved
Size of array is 20
deleted array of size 20
Size of array is 30
deleted array of size 30
Array of size 40 is moved
deleted array of size 0
Size of array is 40
deleted array of size 40
deleted array of size 0

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。