c++ - 复制构造函数(深复制)c++

标签 c++ constructor deep-copy

我正在做一项作业,要求在构造带指针的类时编写 Big 3 的函数实现。我似乎在使用复制构造函数时遇到了问题。我认为我正确地完成了另外 2 项。

class RealBox
{
private:
  float* m_reals;                     // Array of Real Numbers
  int m_boxsize;                      // number of Real Numbers in this box


public:
  // Purpose: Constructs an Real-Box
        // Preconditions:
        //     's' is greater than 0;
  // Postconditions:
  //     m_reals points to a dynamically allocated array of size 's'
  //     all elements of m_reals[] are initiallized to 'a'.

  RealBox(int s, float a);



  /*
   * --------- Big 3 Member Functions -----------
   */

  // Purpose: Destructor
  // Postconditions: m_reals[] deallocated
  ~RealBox();

  // Purpose: Operator=, performs a deep copy of 'rhs' into 'this' RealBox
  // Parameters: rhs, RealBox to be copied
  // Returns: *this
  // Postconditions: *this == rhs
  const RealBox& operator=(const RealBox& rhs);

  // Purpose: Copy Constructor
  // Parameters: rhs - RealBox to be copied
  // Postconditions:  *this == rhs
  RealBox(const RealBox& rhs);


  /*
   * ----- Simple Accessor Operations -----
   */

  // Purpose: Sets a value in the RealBox
  // Parameters: 'i' location to set
  //             'x' value to store
  // PreConditions: 'i' is between the boundaries of the RealBox
  // Postconditions:  element 'i' in the RealBox is set to 'x'
        void set( int i, float x);


  /*
   * ----- Complex Accessor Operations -----
   */

  // Purpose: prints the RealBox
  friend std::ostream& operator<< (std::ostream& out,
                                   const RealBox& box);
}; // RealBox

#include "realbox.h"
#include <iostream>
using namespace std;

RealBox::RealBox(int s, float a)
{
 m_reals = new float[s];
 for (int i=0; i < s; i++)
 {
  m_reals[i] = a;
 }
}

RealBox::~RealBox()
{
 delete [] m_reals;
 m_reals = NULL;
}
const RealBox& RealBox::operator =(const RealBox& rhs)
{
 if(this != &rhs)
   *this = rhs;
 return(*this);
}

RealBox::RealBox(const RealBox& rhs)
{
 m_reals = new float[m_boxsize];
 *this = rhs.m_reals;
}


void RealBox::set(int i, float x)
{
 m_reals[i] = x;
}

std::ostream& operator<< (std::ostream& out, const RealBox& box)
{
 out <<"[ ";
 for (int i = 0; i < box.m_boxsize; i++)
 {
  out << box.m_reals[i] << ", ";
 }
 out <<"]"<< endl;
 return(out);
}

当我尝试编译时,出现错误:

realbox.cpp: In copy constructor ‘RealBox::RealBox(const RealBox&)’: realbox.cpp:33:8: error: no match for ‘operator=’ (operand types are ‘RealBox’ and ‘float* const’)

*this = rhs.m_reals; ^ realbox.cpp:33:8: note: candidate is:

realbox.cpp:23:16: note: const RealBox& RealBox::operator=(const RealBox&) const RealBox& RealBox::operator =(const RealBox& rhs) ^ realbox.cpp:23:16: note: no known conversion for argument 1 from ‘float* const’ to ‘const RealBox&’

我认为我的 operator = overload 也有问题,但我不确定到底出了什么问题。直到我开始尝试修复它才给我那个错误。它试图说我正在比较两种不同的数据类型,但我不确定这是怎么发生的。

最佳答案

这一行:

*this = rhs.m_reals;

尝试分配 float*RealBox目的。这两种类型是不兼容的。

其次,你初始化失败m_boxsize当您构建对象时。

你想要做的是这样的:

RealBox::RealBox(const RealBox& rhs) 
{
  m_boxsize = rhs.boxsize;
  m_reals = new float[m_boxsize];
  for (int i = 0; i < m_boxsize; ++i )
     m_reals[i] = rhs.m_reals[i];
}

这可以缩短为:

RealBox::RealBox(const RealBox& rhs) : m_boxsize(rhs.m_boxsize), 
                                        m_reals(new float[rhs.m_boxsize])
{  
   std::copy(rhs.m_boxsize, rhs.m_boxsize + m_boxsize, m_reals);
}

此外,您的其他构造函数需要初始化 m_boxsize变量:

RealBox::RealBox(int s, float a) : m_boxsize(s)
{
   m_reals = new float[s];
   for (int i=0; i < s; i++)
       m_reals[i] = a;
}

这也可以缩短为:

RealBox::RealBox(int s, float a) : m_boxsize(s), m_reals(new float[s])
{
   std::fill( m_reals, m_reals + s, a);
}

std::fillstd::copy<algorithm> 中定义标题。


一旦你解决了这个问题,赋值运算符就非常简单了:

#include <algorithm>
//...
RealBox& RealBox::operator =(RealBox rhs)
{
    std::swap(rhs.m_reals, m_reals);
    std::swap(rhs.m_boxsize, m_boxsize);
    return *this;
}

复制/交换习语的使用使这一切成为可能。尽可能简单。

What is the copy-and-swap idiom?

关于c++ - 复制构造函数(深复制)c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28756445/

相关文章:

swift - 具有包含数组的元素的数组的深拷贝?

c# - 30% 的时间解决方案重建失败

c++ - 为什么像 1.82 这样的简单 double 最终会变成 1.819999999645634565360?

c# - 可空非引用类型变量是否需要 new()?

java - 我的类的构造函数不起作用

ruby - 如何复制嵌套数组并确保副本是原始数组的完整副本

java - 添加新字段时如何避免破坏克隆/复制方法?

c++ - 这个从后缀数组获取 LCP 的代码是如何工作的?

c++ - 创建线程时出现段错误

C++更改构造函数中的函数解析优先级