当对象作为函数的参数或返回值时,可能会产生一些不必要的中间对象

  1. #include <iostream>
  2. class Cat {
  3. int m_age;
  4. public:
  5. Cat(int age = 0):m_age(age){
  6. std::cout << "Cat(int age = 0):m_age(age)" << std::endl;
  7. };
  8. Cat(const Cat &cat):m_age(cat.m_age){
  9. std::cout << "Cat(const Cat &cat):m_age(cat.m_age)" << std::endl;
  10. }
  11. ~Cat(){
  12. // std::cout << "~Cat()" << std::endl;
  13. }
  14. };
  15. void test(Cat cat){
  16. }

外界使用

  1. int main(int argc, const char * argv[]) {
  2. Cat cat1; //创建一个对象,会调用构造函数
  3. test(cat1);//函数调用,cat1对象作为函数的参数,相当于Cat cat = cat1 利用已经存在的对象创建一个新对象,会调用拷贝构造函数
  4. return 0;
  5. }

解决方案:
我们传递对象的目的通常是在函数里面使用外界传递来的对象。使用引用或者指针做为函数的参数(地址传递),就能避免产生临时对象。

  1. void test(Cat &cat){
  2. }
  1. void test(Cat *cat){
  2. }

建议在C++里面不要使用对象作为函数的参数或返回值。

匿名对象

就是没有名字的对象。

  1. Cat cat1; //这种是有名字的对象,对象名字叫cat1
  1. Cat * p = new Cat(); //这种是有名字的对象,对象名字是一个指针指向叫p

没有名字的对象

  1. Cat();

一般这种对象只会临时的用一次,用完后就会调用析构函数。