qfedu-cpp-level/day3/d7.cpp

61 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 拷贝构造函数的调用时机
// 编译器优化,不会调用拷贝构造函数,而是直接创建一个返回值的引用
#include <iostream>
using namespace std;
class A
{
public:
int x = 0;
public:
A()
{
cout << this << " A()" << endl;
}
A(const A &other)
{
this->x = other.x;
cout << this << " A(const A &other)" << endl;
}
~A()
{
cout << this << " ~A()" << endl;
}
};
void test1(A &a) // ?是否调用拷贝构造函数
// void test1(A a) // ?是否调用拷贝构造函数
{
cout << "test1(A a) a.x = " << a.x << endl;
// 当函数结束时a 释放,会调用析构函数
}
A test2() // 不要声明为 A &test2(), 因为返回对象时,会释放局部对象,导致返回的引用指向一个已经释放的对象
{
A a1; // 局部的类对象, 没有执行拷贝构造函数
a1.x = 1;
cout << "test2() a1.x = " << a1.x << endl;
return a1; // 释放局部对象 a1
}
void test3()
{
cout << "tsss = " << endl;
A a2 = test2(); // 返回 A 类的对象,没有调用拷贝构造函数,只是创建了一个 test2() 返回值的引用
cout << "test3() a2.x = " << a2.x << endl;
}
int main()
{
A a0;
test1(a0); // 作为值传递,调用拷贝构造函数
// test3();
cout << "over" << endl;
return 0;
}