莉莉娅雀氏想笑 2023-03-03 16:03 采纳率: 100%
浏览 22
已结题

return返回对象做了什么

猜测:带cp的是匿名对象,由return产生,他调用复制构造函数复制了st,复制完后st的作用域结束,调用析构。匿名对象作为test的返回值,此时若有变量接收则进行赋值,在test函数结束后对匿名对象析构

上代码:


#include <iostream>
using namespace std;
class Student
{
public:
    Student() {
        id = 99;
        copy = false;
        cout << "Constructor student-" << id << (copy ? "cp" : "") << " is called." << endl;;
    }
    Student(int i):id(i) {
        copy = false;
        cout << "Constructor student-" << id << (copy ? "cp" : "") << " is called." << endl;;
    }
    Student(Student& st) {
        id = st.id;
        copy = true;
        cout << "Copy constructor student-" <<  id << (copy ? "cp" : "") << " is called." << endl;;
    }
    ~Student(){
        cout << "Deconstructor student-" << id << (copy?"cp":"") << " is called." << endl;
    }
private:
    int id;
    bool copy;
};


//测试
Student test() {
    Student st(1);
    return st;
}

int main()
{
    Student s99;
    test();
    Student s2(2);
}

//运行结果
Constructor student-99 is called.
//test内    
Constructor student-1 is called.
Copy constructor student-1cp is called.
Deconstructor student-1 is called.
Deconstructor student-1cp is called.
//test内    
Constructor student-2 is called.
Deconstructor student-2 is called.
Deconstructor student-99 is called.
  • 写回答

1条回答 默认 最新

  • 於黾 2023-03-03 16:33
    关注

    你理解的不对
    根本不存在匿名对象
    Student st
    st不是对象的名字吗,哪里匿名了
    c++里就不存在匿名对象
    只有匿名函数

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 3月11日
  • 已采纳回答 3月3日
  • 创建了问题 3月3日

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题