From standard: “The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except…” (exceptions do not apply). An example from the standard that works fine:
struct S { int mi; const std::pair<int,int>& mp; };
S a { 1, {2,3} };
If I add a constructor, the referenced object is destructed after S
is instantiated. Am I missing something?
#include <iostream>
#include <vector>
using namespace std;
// added just to catch the destructor call
struct Pair : public pair<int, int>
{
Pair() : pair<int, int>{ 1, 2 } {}
~Pair() { cout << "~Pairn"; }
};
struct S
{
const Pair& mp;
S(const Pair& p) : mp{ p } {}
void print() const { cout << mp.first << ' ' << mp.second << 'n'; }
};
int main()
{
S p{ Pair() }; // outputs "~Pair"
p.print(); // outputs "1 2"; ub, probably
}