我需要一个非默认的拷贝构造函数和赋值运算符(它包含指针列表)的类。有没有减少拷贝构造函数和赋值操作符之间的重复代码的任何通用的方式?

有帮助吗?

解决方案

有是用于编写自定义拷贝构造函数和赋值操作符,在所有情况下工作没有“一般的方式”。但是,有一个名为成语“拷贝 - & - 交换”:

 class myclass
 {
    ...
 public:
    myclass(myclass const&);

    void swap(myclass & with);

    myclass& operator=(myclass copy) {
        this->swap(copy);
        return *this;
    }

    ...
};

这是非常有用的许多(但不是全部)的情况。有时候,你可以做的更好。载体或字符串可以具有重新使用分配的存储,如果它是足够大的一个更好的分配。

其他提示

因子出公共代码的私有成员函数。一个简单的(而设计的)示例:

#include <iostream>

class Test
{
public:
  Test(const char* n)
  {
    name = new char[20];
    strcpy(name, n);
  }

  ~Test()
  {
    delete[] name;
  }

  // Copy constructor
  Test(const Test& t)
  {
    std::cout << "In copy constructor.\n";
    MakeDeepCopy(t);
  }

  // Assignment operator
  const Test& operator=(const Test& t)
  {
    std::cout << "In assignment operator.\n";
    MakeDeepCopy(t);
  }

  const char* get_name() const { return name; }

private:
  // Common function where the actual copying happens.
  void MakeDeepCopy(const Test& t)
  {        
    strcpy(name, t.name);
  }

private:
  char* name;
};

int
main()
{
  Test t("vijay");
  Test t2(t); // Calls copy constructor.
  Test t3(""); 
  t3 = t2; // Calls the assignment operator.

  std::cout << t.get_name() << ", " << t2.get_name() << ", " << t3.get_name() << '\n';

  return 0;
}
My &My::operator = (My temp)  // thanks, sellibitze
{
    swap (*this, temp);
    return *this;
}

和实施一个专门std::swap<> (My &, My &)

正如已经指出的相当多的海报,具有操作者=创建一个新的 与拷贝构造对象,然后使用交换是用于不常见的技术有在操作者复制代码=

这是说,我想指出一些亲和这种技术的一个反面,以帮助您确定它是否是合适的。

临 - 异常安全

如果你的对象有资源需求可能导致遥,假设交换不会抛出,这种技术提供异常安全的有力保障(无论该对象被分配到已经采取的其他对象的值或者是不变)。

CON - 资源足迹

这种技术的一个问题是,它需要一个完整的新对象旧的被释放之前被创建。如果你的对象需要大量的资源,这可能是一个问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top