首页  >  问答  >  正文

c++11 - 这段 C++ 代码究竟创建了多少个对象?

class stu{
public:
    int age;
    int score;
    stu() = default;
    stu(int a, int s):
        age(a), score(s) { cout << " i am constructor" << endl;}
    stu(const stu& stu1):
        age(stu1.age), score(stu1.score) { cout << " i am copy constructor" << endl;}
};
const stu combine(const stu &stu1, const stu &stu2)
{
    stu new_stu(stu1.age + stu2.age, stu1.score + stu2.score);
    return  new_stu;
}
int main()
{
    stu stu1(22,100);
    stu stu2(23,99);
    stu result(combine(stu1, stu2));
    cout << result.age << result.score << endl;
}

我的理解是应该创建了四个对象,其中一个是临时对象,由combine(stu1, stu2)函数返回时创建。类的构造函数执行打印一行字符串的功能,通过有多少行字符串可以推出执行了多少次构造函数,代码在运行时只有三行字符串,意味着只创建了三个对象,究竟哪里有问题??

巴扎黑巴扎黑2714 天前846

全部回复(3)我来回复

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:07:32

    1. 首先纠正一点, 临时对象由combine返回是没有错的, 但是这里调用的是拷贝构造函数,而非构造函数.然后result声明的时候又调用了一次构造函数,所以最终的次数是 两次构造函数+一次拷贝构造函数+一次构造函数

    2. 那疑问来了, 为啥这里面的拷贝构造函数完全没有体现呢, 这是因为编译器会略过这次拷贝构造函数而直接执行构造函数, 所以结果就变成了三次构造函数, 相关内容可以参考c++ primer十三章.

    虽然编译器会跳过了拷贝构造函数, 不过要保证类的拷贝构造函数可以访问的(非private), 可以这么验证会报错.

    class stu{
    public:
        int age;
        int score;
        stu() = default;
        stu(int a, int s):
            age(a), score(s) { cout << " i am constructor" << endl;}
    prvate:
        //虽然编译器绕过了拷贝构造函数,但是仍然需要拷贝构造函数可见.这里会编译错误
        stu(const stu& stu1):
            age(stu1.age), score(stu1.score) { cout << " i am copy constructor" << endl;}
    };

    回复
    0
  • 高洛峰

    高洛峰2017-04-17 13:07:32

    这是RVO(Return Value Optimization)

    参考:https://en.wikipedia.org/wiki/Return_value_optimization

    回复
    0
  • 迷茫

    迷茫2017-04-17 13:07:32

    生成了五个对象
    stu1 +1
    stu2 +1
    new_stu +1
    const stu +1
    result +1

    编译器默认会开启返回值优化
    在用gcc编译时加 -fno-elide-constructors选项就可以关掉此优化。
    运行编译后的程序的结果如下:
    i am constructor
    i am constructor
    i am constructor
    i am copy constructor
    i am copy constructor
    45199

    回复
    0
  • 取消回复