返回对象与默认构造函数签名中的引用

Returning object vs. reference in default constructor signature

本文关键字:引用 构造函数 对象 默认 返回      更新时间:2023-10-16

本质上,两者之间有什么区别:

const Date& default_date()
{
    static Date dd(2001,Date::Jan,1);
    return dd;
}

const Date default_date()
{
    static Date dd(2001,Date::Jan,1);
    return dd;
}

函数签名真的重要吗?我不认为Date&是像*Date这样的类型,所以我不确定这有什么区别。它只是阻止在退货时制作副本吗?但是你不会回来&dd吗?

第一个函数返回对静态对象的 const 引用,因此您可以执行以下操作:

const Date& d = default_date(); // d is a reference to the original

Date d = default_date(); // d is a copy of the original, 
                         // provided there is a copy constructor

第二个创建static Date对象的副本,因此您只能获取副本

Date d = default_date(); // d is a copy of the original

返回 &dd 将返回静态对象的地址,然后可以将其分配给指向 Date 的指针。return 语句的语法与按引用返回或按值返回的语法相同。语义取决于函数的返回类型。

请注意,在C++中,default_date等函数不称为构造函数。