weixin_46029833 2020-06-15 17:09 采纳率: 0%
浏览 179
已采纳

copy ctor 和 operator=

#include <iostream>
#include <string>

class NoName { 
public: 
    NoName(): pstring(new std::string), i(0), d(0) {   
        std::cout << "default ctor is called" << std::endl; 
    }   

    NoName(const NoName& other) 
        : pstring(new std::string(*(other.pstring))), i(other.i), d(other.d) { 
            // C++ 默认的copy ctor是 
            // pstring(other.pstring),这是浅拷贝,是错的 
            std::cout << "copy ctor is called" << std::endl; 
        }   

    NoName& operator=(const NoName rhs) { 
        std::cout << "operator= is called" << std::endl; 
        pstring = new std::string; 
        *pstring = *(rhs.pstring); 
        i = rhs.i; 
        d = rhs.d; 
        // C++ 默认的operator=是 
        // pstring = ths.pstring是浅拷贝,是错误的 
        return *this; 
    }   

private: 
    std::string *pstring; 
    int i; 
    double d; 
}; 

int main()
{
    std::cout << std::endl <<"------test------" << std::endl;
    std::cout << "NoName x, y:" << std::endl;
    NoName x, y;
    std::cout << std::endl;

    std::cout << "NoName z(x):" << std::endl;

    NoName z(x);
    std::cout << std::endl;

    std::cout << "x = y:" << std::endl;
    x = y;   
    std::cout << std::endl;

    return 0;
}

为什么x= y这一步即调用了copy ctor又调用了operator=

------test------
NoName x, y:
default ctor is called
default ctor is called

NoName z(x):
copy ctor is called

x = y:
copy ctor is called
operator= is called
  • 写回答

1条回答 默认 最新

  • 胖狗子修行之路 2020-06-15 18:59
    关注

    赋值运算符的参数不是引用会导致调用拷贝构造函数,需要改成:

        NoName& operator=(const NoName& rhs) { 
            std::cout << "operator= is called" << std::endl; 
            pstring = new std::string; 
            *pstring = *(rhs.pstring); 
            i = rhs.i; 
            d = rhs.d; 
            // C++ 默认的operator=是 
            // pstring = ths.pstring是浅拷贝,是错误的 
            return *this; 
        }   
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大