Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialise a reference member in the default constructor?

Question says it all really.

Would it be better to use const pointer members instead if I were to implement the default constructor?

like image 687
Armada Avatar asked Sep 14 '25 14:09

Armada


1 Answers

You need to use the member initialization list:

struct foo
{
  const int& ref;
  foo() : ref(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:

A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

like image 108
Joseph Mansfield Avatar answered Sep 17 '25 04:09

Joseph Mansfield