I was reading C++ Faq Second Edition , faq number 32.08 .
FAQ says that parameter passed by const reference and returned by const reference can cause dangling reference.
But it is ok if parameter is passed by reference and returned by reference.
I got it that it is unsafe in case of const reference but how is it safe in case when parameter is non const reference.
Last line of FAQ says "Note that if a function accepts a parameter by non-const reference (for example, f(string& s)), returning a copy of this reference parameter is safe because a temporary cannot be passed by non-const reference."
Need some insight on this!!
You must either change the method to being non-const, return a const reference, or make Bar exempt of the promise by marking it as mutable . E.g.: mutable int Bar; The mutable keyword tells the compiler that the logical constness of the object does not depend on the state of Bar .
Passing By Reference To Const in C++ C++ is an example of a message-passing paradigm language, which means that objects and values are passed to functions, which then return further objects and values based on the input data.
What is one benefit of declaring the parameter as a const reference instead of declaring it as a regular object? Actually, objects cannot be passed as regular variables, because they require a constructor call. Therefore, a const reference is the only way to pass class instances to functions.
The reference parameters are initialized with the actual arguments when the function is called. This example outputs 6 . Pass-by-references is more efficient than pass-by-value, because it does not copy the arguments. The formal parameter is an alias for the argument.
if you have like
const Foo & bar(const Foo &f) { return f; }
and call it like
const Foo &ret = bar(Foo());
This compiles, but the problem is that now 'ret' is a dangling reference, because the temporary object created by the call to Foo() gets freed after bar returns. The detailed execution sequence here is:
However, if you had Foo declared as
Foo & bar(Foo &f) { return f; }
then your call bar(Foo()) would not be accepted by compiler. When you pass a temporary object to a function, you can only take it by const reference or as a copy; this is part of the language definition.
Temporaries can be passed by const reference - when the function returns the temporaries are destoyed, so the caller is left with a dangling ref.
For example:
#include <iostream>
using namespace std;
int const& output( int const& x)
{
cout << x << endl;
return x;
}
int main ()
{
int a = 1;
int const& ref1 = output( a); // OK
int const& ref2 = output(a+1); // bad
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With