返回对象与默认构造函数签名中的引用
Returning object vs. reference in default constructor signature
本质上,两者之间有什么区别:
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
等函数不称为构造函数。
相关文章:
- 在类构造函数中传递对外部函数的引用
- 在 c++ 中将变量作为结构构造函数中的引用传递
- C++ 尝试在不存在的构造函数中引用已删除的函数(使用 rapidJson)
- 移动构造函数和右值引用
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 在引用初始化中使用已删除的复制构造函数进行复制初始化
- C++:右值引用构造函数和复制省略
- 当有右值构造函数可用时,为什么从右值调用类引用构造函数重载?
- 引用构造函数时链接失败
- 为什么调用转发引用构造函数而不是复制构造函数?
- 为什么使用已删除的右值引用构造函数?
- 对 std::Optional 的转发引用构造函数的约束
- 模板是否应该为不同类型的参数制作非 Rvalue 引用构造函数/赋值
- 我是否应该对非引用构造函数参数手动调用move
- 使用左值引用错误地调用了Rvalue引用构造函数
- C++未定义的引用构造函数错误
- 调用左值引用构造函数而不是右值引用构造函数
- C++引用构造函数语法
- 不能引用构造函数的地址