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

Does the constructor of a class return a reference of the class type or just a piece of memory?

本文关键字:返回 一段 内存 构造函数 类型 引用      更新时间:2023-10-16

据我所知,构造函数没有返回类型。但在下面的代码中,看起来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 ctorn";
        }
        c(){
        //  cout<<"nc ctorn";
        }
        ~c(){
        //  cout<<"nc dtorn";
        }
};
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() Donen";
     return 0;
}

o/p此处:

 addr1 = 0xbfc3c248
 addr2 = 0xbfc3c24c
 addr3 = 0xbfc3c214
 main() Done

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

在代码中执行以下操作的部分:

const c &co = c(3);

可以这样说:

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

但是,您正在创建一个临时对象,并将引用绑定到它。通常,临时对象的生存期在该语句/序列点的末尾结束。然而,C++标准保证了其使用寿命的延长。