【问题标题】:Calling class constructor from myself in ::operator =在 ::operator = 中从我自己调用类构造函数
【发布时间】:2020-10-07 23:45:17
【问题描述】:

我正在为我的 c++ 代码编写 class::operator=,并尝试在此代码 sn-p 中克隆类参数 right

myClass & myClass::operator =(const myClass &right){
     myClass *abcde = new myClass(right); 
     myClass coolvar(right); //this and the previous line work, but don't update the class

     *this = *abcde; //uses = operator, so infinitely loops

     myClass *this = new myClass(right); // doesn't work [expected unqualified-id]
     myClass this(right); // doesn't work [expected unqualified-id]
}

但是,我找不到正确重写指针的方法,比如使用*this = *abcde,或者像底部两行那样调用类本身的构造函数。我该怎么办?

【问题讨论】:

  • 您需要手动更新字段。这些试图利用复制构造函数的快捷方式将不起作用。此外,您应该接受引用 const myClass &right 以避免不必要的复制构造函数调用。
  • 注意:通过按值传入right,您将接近能够应用Copy and Swap Idiom.
  • 如果我理解你的意图,你想调用复制构造函数来构造已经构造好的*this?那么到程序结束时,构造函数调用会比析构函数调用多吗?这往往是灾难的根源。
  • @user4581301 默认不复制和交换。它经常扼杀你的表现。
  • 不要使用手动内存管理,所有问题都会迎刃而解。

标签: c++ constructor operator-keyword


【解决方案1】:

我不认为你真的想构造一个对象。正确的做法是提供一个用户定义的std::swap 并在一个新构造的对象上使用:

std::swap(*this, other);

见: What is the copy-and-swap idiom?

如果你想复制对象中的数据也可以试试std::memcy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2018-10-19
    • 1970-01-01
    相关资源
    最近更新 更多