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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了