类的构造函数是返回类类型的引用还是只返回一块内存?

时间:2014-04-13 16:14:16

标签: c++

据我所知,构造函数没有返回类型。但是在下面的代码中它看起来ctor确实返回一个const引用对象(ctor有一个返回类型为const引用的aclass,它是隐藏的?),(或)返回一段const引用类型的内存(Q1)?或者这是别的(Q1)?这些对象是有效的,由ctor(Q2)返回,它们是否相当于c stack_object;(Q2)?请分享您的想法。

#include<iostream>
using namespace std;    

class c{
    public:
        int x = 88;
        c(int i){
            x=i; 
        //  cout<<"\nc1 ctor\n";
        }
        c(){
        //  cout<<"\nc ctor\n";
        }
        ~c(){
        //  cout<<"\nc dtor\n";
        }
};

int f(){
     const  c & co1 = c();  //ctor returns a const reference obj of type c class
     c &ref = const_cast<c&>(co1);  //casting away const
     cout<<"\n addr3 = "<<&ref<<"\n";  //another new address
     ref.x = 99;
     //cout<<ref.x;
}


int main(){
    const  c &co = c(3);   
    c *p = const_cast<c*>(&co);

    cout<<"\n addr1 = "<<p<<"\n";   
    //cout<<p->x;  //out puts 3      
    p->x = 11; //just assigning some new values

    const  c & co1 = c();
    c *p1 = const_cast<c*>(&co1);

    cout<<"\n addr2 = "<<p1<<"\n";  //new address
    //cout<<"\n"<<p1->x;

    f();

    cout<<"\n main() Done\n";
     return 0;
}

o / p在这里:

 addr1 = 0xbfc3c248

 addr2 = 0xbfc3c24c

 addr3 = 0xbfc3c214

 main() Done

1 个答案:

答案 0 :(得分:2)

正如您所确定的,构造函数不会返回任何内容;它没有返回类型。

在你的代码中做一些像这样的事情:

const c &co = c(3);

说出以下内容是有效的:

  

表达式c(3)c类型的右值。

但是,您正在创建一个临时对象,并绑定对它的引用。通常,临时的生命周期在该语句/序列点的末尾结束。但是,C ++标准保证其lifetime is prolonged