M
Matthias Kaeppler
Hello,
during a discussion on a C++ internet forum, some question came up
regarding references and the lifetime of the objects they alias.
I can't find any clear wording on that in the draft standard. Example
12.2 in the standard document illustrates that temporaries bound to
references-to-const live as long as the reference does.
But does it e.g. matter if the temporary was created in scope of a
function body and has to outlive the function call? And what happens
with this temporary when everything else from the stack has to be
destroyed except the temporary? Is it copied to a new location in memory?
Examples:
int f1()
{
int a=1;
return a;
}
int& f1r() // note that the return type changed
{
int a=1;
return a;
}
int f2()
{
int a(1),b(2);
return a+b;
}
int& f2r()
{
int a(1),b(2);
return a+b;
}
....
/* 1 */ const int& ref = f1();
/* 2 */ const int& ref = f1r();
/* 3 */ const int& ref = f2();
/* 4 */ const int& ref = f2r();
/* 5-8 */ <like 1-4 but without const qualifier>
Can you comment expressions 1-8 regarding their behavior (defined,
undefined) and the lifetime of the objects which are aliased?
Thanks a lot.
during a discussion on a C++ internet forum, some question came up
regarding references and the lifetime of the objects they alias.
I can't find any clear wording on that in the draft standard. Example
12.2 in the standard document illustrates that temporaries bound to
references-to-const live as long as the reference does.
But does it e.g. matter if the temporary was created in scope of a
function body and has to outlive the function call? And what happens
with this temporary when everything else from the stack has to be
destroyed except the temporary? Is it copied to a new location in memory?
Examples:
int f1()
{
int a=1;
return a;
}
int& f1r() // note that the return type changed
{
int a=1;
return a;
}
int f2()
{
int a(1),b(2);
return a+b;
}
int& f2r()
{
int a(1),b(2);
return a+b;
}
....
/* 1 */ const int& ref = f1();
/* 2 */ const int& ref = f1r();
/* 3 */ const int& ref = f2();
/* 4 */ const int& ref = f2r();
/* 5-8 */ <like 1-4 but without const qualifier>
Can you comment expressions 1-8 regarding their behavior (defined,
undefined) and the lifetime of the objects which are aliased?
Thanks a lot.