猜测:带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.