return返回对象做了什么

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

上代码:


#include 
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.

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