如何在默认构造函数中初始化引用成员? [英] How can I initialise a reference member in the default constructor?
本文介绍了如何在默认构造函数中初始化引用成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题说的一切真的。
如果我实现默认构造函数,最好使用const指针成员?
Would it be better to use const pointer members instead if I were to implement the default constructor?
推荐答案
您需要使用成员初始化列表:
You need to use the member initialization list:
struct foo
{
const int& ref;
foo() : ref(some_value()) { }
}
确保 some_value()
不会给你一个临时。它将只有它的生命延长到构造函数的结束:
Make sure some_value()
doesn't give you a temporary. It will only have its life extended until the end of the constructor:
临时绑定到构造函数的ctor-initializer中的引用成员12.6.2)持续到构造函数退出。
A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
这篇关于如何在默认构造函数中初始化引用成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文