Strange C++ reference invalidation on return - c++

Have a look at the following code. The goal here is to return a reference through two functions (from ReferenceProvider::getReference() to getRef() to main()):
#include <tchar.h>
#include <assert.h>
#include <string>
class BaseClass {
public:
virtual void write() const {
printf("In base class\n");
}
};
typedef BaseClass* BaseClassPointer;
class ChildClass : public BaseClass {
public:
virtual void write() const {
printf("In child class\n");
}
};
typedef ChildClass* ChildClassPointer;
//////////////////////////////////////////////////////////////////////////
ChildClass* g_somePointer = new ChildClass();
class ReferenceProvider {
public:
const BaseClassPointer& getReference() {
const BaseClassPointer& val = g_somePointer;
return val;
}
};
ReferenceProvider g_provider;
const BaseClassPointer& getRef() {
std::string test;
const BaseClassPointer& val = g_provider.getReference();
return val;
}
int _tmain(int argc, _TCHAR* argv[]) {
BaseClass* child = getRef();
assert(child == g_somePointer);
child->write();
return 0;
}
Now, when debugging this code (in Visual C++), breaking at return val; in getRef() will give you a screen like this:
Notice how the values of g_somePointer and val are the same. Now, step over the return statement and you'll get a screen like this:
Notice how val has become invalid (0xcccccccc). This is probably because the stack of getRef() has been cleared and val is no longer available.
The problem now is that child in _tmain() will get this invalid value (0xcccccccc) rendering child unusable. So my first (and main) question is: How to do this correctly?
(Please note that this is just an boiled down example from some other code I've been working on. It needs to be structured like with, including using references to pointers.)
What's making this whole thing very strange (and hard to debug) is that the function getRef() works under some conditions:
If you change the type of g_somePointer to BaseClass* (from ChildClass*)
If you remove the local variable in getRef() (i.e. the line std::string test;)
In both cases the reference variable val (in getRef()) will not become invalid and the function will return the correct pointer address. Can anybody explain this to me?

The problem is here:
const BaseClassPointer& val = g_somePointer;
Since g_somePointer has a different type (ChildClass* is convertible to BaseClass*, but is not the same type), val cannot refer directly to g_somePointer. Instead, a temporary copy is made, converted to the correct type, and val refers to that.
The temporary only lasts as long as val, going out of scope at the end of the function, so the function returns an invalid reference.
If you change the type of g_somePointer to BaseClass* (from ChildClass*)
In that case, no pointer conversion is required, and so val can refer directly to g_somePointer. The code is then correct, but fragile.
If you remove the local variable in getRef() (i.e. the line std::string test;)
With the string variable, there is a destructor call at the end of the function, which overwrites the defunct stack frame that contains the temporary pointer. Without it, nothing overwrites the memory, so the code appears to work - which is unfortunate, as it makes the error much harder to notice.

You can never return a reference to a local object: it will always go out of scope when the function is exited. Sometimes it may appear as if it works but this is just because the data is normally not change when the stack pointer is adjusted.

To explain what's going on:
const BaseClassPointer& val = g_somePointer;
This line is the problem. Let's do away with the typedef:
BaseClass* const& val = g_somePointer;
Here, the type of g_somePointer is ChildClass*. In order to assign it to a BaseClass*, a conversion is needed. From that conversion, a temporary pointer is introduced. That pointer is bound to a reference-to-const, which extends the temporaries lifetime until the reference dies, which is exactly the case after your return val; statement. At that point, the temporary base-class pointer doesn't exist anymore and you have undefined behaviour.
To avoid all that mess, just return a BaseClass*.

You don't want to do something like that. Returning a reference to local memory is the same as returning the address of local memory, which is undefined behavior. All sorts of things can go wrong (or by chance, things can go right).

If you want the "val" to "survive", getReference() method should return a reference to a static object. Is that "static" going to work in your current architecture is another question.

You're returning a const reference to the local val instead of the returned getRef().
Also, how do you transform the pointer to a reference?
const BaseClassPointer& val = g_somePointer;
return val;
won't work if g_somePointer is a pointer - did you use *g_somePointer or similar?

Related

Extending the lifetime of a temporary object without copying it

Consider the following code:
#include <utility>
#include <iostream>
struct object {
object(const object&) = delete;
object(object&&) = delete;
object() {std::clog << "object::object()\n";}
~object() {std::clog << "object::~object()\n";}
void operator()() const {std::clog << "object::operator()()\n";}
};
struct wrapper {
const object& reference;
void operator()() const {reference();}
};
template <class Arg>
wrapper function(Arg&& arg) {
wrapper wrap{std::forward<Arg>(arg)};
return wrap;
}
int main(int argc, char* argv[]) {
wrapper wrap = function(object{}); // Let's call that temporary object x
wrap();
return 0;
}
I am really surprised that it prints:
object::object()
object::~object()
object::operator()()
Question 1: Why is the lifetime of object x not extended past the function call even if a const reference has been bound to it?
Question 2: Is there any way to implement the wrapper so that it would extend the lifetime of x past the function call?
Note: The copy and move constructors of the object have been explicitly deleted to make sure only one instance of it exists.
Why is the lifetime of object x not extended past the function call even if a const reference has been bound to it?
Technically, the lifetime of the object is extended past the function call. It is not however extended past the initialization of wrap. But that's a technicality.
Before we dive in, I'm going to impose a simplification: let's get rid of wrapper. Also, I'm removing the template part because it too is irrelevant:
const object &function(const object &arg)
{
return arg;
}
This changes precisely nothing about the validity of your code.
Given this statement:
const object &obj = function(object{}); // Let's call that temporary object x
What you want is for the compiler to recognize that "object x" and obj refer to the same object, and therefore the temporary's lifetime should be extended.
That's not possible. The compiler isn't guaranteed to have enough information to know that. Why? Because the compiler may only know this:
const object &function(const object &arg);
See, it's the definition of function that associates arg with the return value. If the compiler doesn't have the definition of function, then it cannot know that the object being passed in is the reference being returned. Without that knowledge, it cannot know to extend x's lifetime.
Now, you might say that if function's definition is provided, then the compiler can know. Well, there are complicated chains of logic that might prevent the compiler from knowing at compile time. You might do this:
const object *minimum(const object &lhs, const object &rhs)
{
return lhs < rhs ? lhs : rhs;
}
Well, that returns a reference to one of them, but which one will only be determined based on the runtime values of the object. Whose lifetime should be extended by the caller?
We also don't want the behavior of code to change based on whether the compiler only has a declaration or has a full definition. Either it's always OK to compile the code if it only has a declaration, or it's never OK to compile the code only with a declaration (as in the case of inline, constexpr, or template functions). A declaration may affect performance, but never behavior. And that's good.
Since the compiler may not have the information needed to recognize that a parameter const& lives beyond the lifetime of a function, and even if it has that information it may not be something that can be statically determined, the C++ standard does not permit an implementation to even try to solve the problem. Thus, every C++ user has to recognize that calling functions on temporaries if it returns a reference can cause problems. Even if the reference is hidden inside some other object.
What you want cannot be done. This is one of the reasons why you should not make an object non-moveable at all unless it is essential to its behavior or performance.
As far as I know, the only case the lifetime if extended if for the return value of a function,
struct A { int a; };
A f() { A a { 42 }; return a`}
{
const A &r = f(); // take a reference to a object returned by value
...
// life or r extended to the end of this scope
}
In your code, you pass the reference to the "constructor" of A class. Thus it is your responsability to ensure that the passed object live longer. Thus, your code above contains undefined behavior.
And what you see would probably be the most probable behavior in a class that do not make reference to any member. If you would access object member (including v-table), you would most likely observe a violation access instead.
Having said that, the correct code in your case would be:
int main(int argc, char* argv[])
{
object obj {};
wrapper wrap = function(obj);
wrap();
return 0;
}
Maybe what you want is to move the temporary object into the wrapper:
struct wrapper {
wrapper(object &&o) : obj(std::move(o)) {}
object obj;
void operator()() const {obj();}
};
In any case, the original code does not make much sense because it is build around false assumption and contains undefined behavior.
The life of a temporary object is essentially the end of the expression in which it was created. That is, when processing wrap = function(object{}) is completed.
So in resume:
Answer 1 Because you try to apply lifetime extension to a context other that the one specified in the standard.
Answer 2 As simple as moving the temporary object into a permanent one.

const reference to a pointer can change the object

const references make sure you can't change the object you're referring to. For example:
int i = 1;
const int& ref = i;
ref = 42; // error, because of a const reference
But if you use a reference to a pointer or a unique_ptr, you can. Example:
class TinyClass {
public:
int var = 1;
void f1() { var = 42; }
};
std::unique_ptr<TinyClass> pointer(new TinyClass);
const std::unique_ptr<TinyClass>& constRef = pointer;
constRef->f1(); // no error
I assume this happens because the pointer itself wasn't changed. But this feels misleading, or like an easy mistake. Is there a simple way to declare a "real" const reference to a pointer? As in: makes sure the object itself is const.
edit: Assume that I can't just change the type of the unique_ptr. A real-world scenario would be that some objects are constructed in a vector<unique_ptr<C>> and some function gets a (const) reference to one of its elements.
The const in const std::unique_ptr<TinyClass>& constRef guarantees that constRef will not point to another object once it set up. It has nothing to do with the object itself.
If you want to prevent changing the object itself:
std::unique_ptr<const TinyClass> ptr_to_const_object;
Edit (after OP's edit):
You can not do anything. Since there is a function which wants const vector<unique_ptr<C>>&, the function clearly tells you that it needs to play with the object inside the pointer (and even the pointer) but it does not need to change the vector items (like adding new item or deleting it).

Do I have to return a pointer from a factory?

Can anyone see any problems with returning an object by value from a factory rather than returning a unique_ptr?
The following compiles and runs correctly for me, but i'm unsure if i've missed something about l-value and r-value reference interactions and lifetimes.
I've the following class hierarchy,
#include <iostream>
struct Reader {
virtual ~Reader() {}
virtual void get(int& val) = 0;
};
struct CinReader : public Reader {
~CinReader() { std::cout << "~CinReader()\n"; }
void get(int& val) override
{
std::cout << "CinReader::get\n";
std::cin >> val;
}
};
struct ConstantReader : public Reader {
void get(int& val) override
{
std::cout << "ConstantReader::get\n";
val = 120;
}
};
I am using the following factory to return instances,
enum class ReaderType { cin = 0, constant = 1 };
Reader&& readerFactoryObj(ReaderType type)
{
switch (type) {
case ReaderType::cin:
return std::move(CinReader());
break;
case ReaderType::constant:
return std::move(ConstantReader());
break;
default:
throw "Unknown Reader type";
}
}
and used as follows,
int main(void)
{
auto&& reader = readerFactoryObj(ReaderType::cin);
int val;
reader.get(val);
}
It works when passed to something that stores a reference to the Reader interface,
class Doubler
{
public:
Doubler(Reader& reader) : mReader(reader) { }
void doubleNum() const;
private:
Reader& mReader;
};
void Doubler::doubleNum() const
{
int val;
mReader.get(val);
std::cout << val * 2 << '\n';
}
int main(void)
{
auto&& reader = readerFactoryObj(ReaderType::cin);
Doubler d(reader);
d.doubleNum();
}
I realise reader isn't of type Reader now, but will be one of its concrete sub-classes.
Are there any problems with passing reader as Reader& and storing it?
Update:
I added a destructor to CinReader and it clearly shows me that its lifetime ends before it's used.
You're returning references to temporary objects. Undefined behavior. The compiler would likely warn you if you didn't trick it with a completely redundant move call.
There are two things you might return from factory-functions:
Pointers. Either std::unique_ptr or std::shared_ptr, not raw pointers, so ownership-semantics are explicit and RAII works.
The object itself by value. For an example, look at std::make_shared, std::allocate_shared and so on.
What you must never do is returning a reference or pointer to storage which will be cleaned up on return, like stack-variables.
The compiler might not catch you, it might seem to work (for a time), but it's undefined behavior.
In your case, returning by pointer would be the right thing, so polymorphism works.
As an aside, don't throw string-literals, throw a std::exception or derived.
Can anyone see any problems with returning an object by value from a factory rather than returning a unique_ptr?
A valid question, but your factory doesn't return by value. Its return type is a reference type, so you're returning by reference.
It works when passed to something that stores a reference to the Reader interface,
No, it only appears to work because your Reader types are stateless and so you happen to get away with using them after their lifetime has ended.
Reader&& readerFactoryObj(ReaderType type)
{
...
return std::move(CinReader());
You are creating a temporary (which is an rvalue) then using std::move to cast it to an rvalue (that's completely redundant) then returning a dangling reference to that temporary. This is really really bad. Don't do that. Ever.
If you want the efficiency and simplicity of move semantics then just make your functions return by value and say return x;, it's easier and does the right thing, unlike doing unnecessary casts and returning dangling references, which is more complicated and wrong.
In your specific case, since your factory wants to return two different types you can't return by value or you'd slice the object and only return the base part. So you need to return by pointer, and you had better return by smart pointer or children will point and laugh at you in the street.
The design problem is that factories generally return an object of unspecified type, which at least implements the desired interface (base class). However, it may (and often will) return objects of a more derived class.
Returning such an object by value would cause slicing. Returning a reference causes lifetime issues (as your code demonstrates). Returning a smart pointer fixes those lifetime issues.

Which are the implications of return a value as constant, reference and constant reference in C++?

I'm learning C++ and I'm still confused about this. What are the implications of return a value as constant, reference and constant reference in C++ ? For example:
const int exampleOne();
int& exampleTwo();
const int& exampleThree();
Here's the lowdown on all your cases:
• Return by reference: The function call can be used as the left hand side of an assignment. e.g. using operator overloading, if you have operator[] overloaded, you can say something like
a[i] = 7;
(when returning by reference you need to ensure that the object you return is available after the return: you should not return a reference to a local or a temporary)
• Return as constant value: Prevents the function from being used on the left side of an assignment expression. Consider the overloaded operator+. One could write something like:
a + b = c; // This isn't right
Having the return type of operator+ as "const SomeType" allows the return by value and at the same time prevents the expression from being used on the left side of an assignment.
Return as constant value also allows one to prevent typos like these:
if (someFunction() = 2)
when you meant
if (someFunction() == 2)
If someFunction() is declared as
const int someFunction()
then the if() typo above would be caught by the compiler.
• Return as constant reference: This function call cannot appear on the left hand side of an assignment, and you want to avoid making a copy (returning by value). E.g. let's say we have a class Student and we'd like to provide an accessor id() to get the ID of the student:
class Student
{
std::string id_;
public:
const std::string& id() const;
};
const std::string& Student::id()
{
return id_;
}
Consider the id() accessor. This should be declared const to guarantee that the id() member function will not modify the state of the object. Now, consider the return type. If the return type were string& then one could write something like:
Student s;
s.id() = "newId";
which isn't what we want.
We could have returned by value, but in this case returning by reference is more efficient. Making the return type a const string& additionally prevents the id from being modified.
The basic thing to understand is that returning by value will create a new copy of your object. Returning by reference will return a reference to an existing object. NOTE: Just like pointers, you CAN have dangling references. So, don't create an object in a function and return a reference to the object -- it will be destroyed when the function returns, and it will return a dangling reference.
Return by value:
When you have POD (Plain Old Data)
When you want to return a copy of an object
Return by reference:
When you have a performance reason to avoid a copy of the object you are returning, and you understand the lifetime of the object
When you must return a particular instance of an object, and you understand the lifetime of the object
Const / Constant references help you enforce the contracts of your code, and help your users' compilers find usage errors. They do not affect performance.
Returning a constant value isn't a very common idiom, since you're returning a new thing anyway that only the caller can have, so it's not common to have a case where they can't modify it. In your example, you don't know what they're going to do with it, so why should you stop them from modifying it?
Note that in C++ if you don't say that something is a reference or pointer, it's a value so you'll create a new copy of it rather than modifying the original object. This might not be totally obvious if you're coming from other languages that use references by default.
Returning a reference or const reference means that it's actually another object elsewhere, so any modifications to it will affect that other object. A common idiom there might be exposing a private member of a class.
const means that whatever it is can't be modified, so if you return a const reference you can't call any non-const methods on it or modify any data members.
Return by reference.
You can return a reference to some value, such as a class member. That way, you don't create copies. However, you shouldn't return references to values in a stack, as that results in undefined behaviour.
#include <iostream>
using namespace std;
class A{
private: int a;
public:
A(int num):a(num){}
//a to the power of 4.
int& operate(){
this->a*=this->a;
this->a*=this->a;
return this->a;
}
//return constant copy of a.
const int constA(){return this->a;}
//return copy of a.
int getA(){return this->a;}
};
int main(){
A obj(3);
cout <<"a "<<obj.getA()<<endl;
int& b=obj.operate(); //obj.operate() returns a reference!
cout<<"a^4 "<<obj.getA()<<endl;
b++;
cout<<"modified by b: "<<obj.getA()<<endl;
return 0;
}
b and obj.a "point" to the same value, so modifying b modifies the value of obj.a.
$./a.out
a 3
a^4 81
modified by b: 82
Return a const value.
On the other hand, returning a const value indicates that said value cannot be modified. It should be remarked that the returned value is a copy.:
For example,
constA()++;
would result in a compilation error, since the copy returned by constA() is constant. But this is just a copy, it doesn't imply that A::a is constant.
Return a const reference.
This is similiar to returning a const value, except that no copy is return, but a reference to the actual member. However, it cant be modified.
const int& refA(){return this->a;}
const int& b = obj.refA();
b++;
will result in a compilation error.
const int exampleOne();
Returns a const copy of some int. That is, you create a new int which may not be modified. This isn't really useful in most cases because you're creating a copy anyway, so you typically don't care if it gets modified. So why not just return a regular int?
It may make a difference for more complex types, where modifying them may have undesirable sideeffects though. (Conceptually, let's say a function returns an object representing a file handle. If that handle is const, the file is read-only, otherwise it can be modified. Then in some cases it makes sense for a function to return a const value. But in general, returning a const value is uncommon.
int& exampleTwo();
This one returns a reference to an int. This does not affect the lifetime of that value though, so this can lead to undefined behavior in a case such as this:
int& exampleTwo() {
int x = 42;
return x;
}
we're returning a reference to a value that no longer exists. The compiler may warn you about this, but it'll probably compile anyway. But it's meaningless and will cause funky crashes sooner or later. This is used often in other cases though. If the function had been a class member, it could return a reference to a member variable, whose lifetime would last until the object goes out of scope, which means function return value is still valid when the function returns.
const int& exampleThree();
Is mostly the same as above, returning a reference to some value without taking ownership of it or affecting its lifetime. The main difference is that now you're returning a reference to a const (immutable) object. Unlike the first case, this is more often useful, since we're no longer dealing with a copy that no one else knows about, and so modifications may be visible to other parts of the code. (you may have an object that's non-const where it's defined, and a function that allows other parts of the code to get access to it as const, by returning a const reference to it.
Your first case:
const int exampleOne();
With simple types like int, this is almost never what you want, because the const is pointless. Return by value implies a copy, and you can assign to a non-const object freely:
int a = exampleOne(); // perfectly valid.
When I see this, it's usually because whoever wrote the code was trying to be const-correct, which is laudable, but didn't quite understand the implications of what they were writing. However, there are cases with overloaded operators and custom types where it can make a difference.
Some compilers (newer GCCs, Metrowerks, etc) warn on behavior like this with simple types, so it should be avoided.
I think that your question is actually two questions:
What are the implications of returning a const.
What are the implications of returning a reference.
To give you a better answer, I will explain a little more about both concepts.
Regarding the const keyword
The const keyword means that the object cannot be modified through that variable, for instance:
MyObject *o1 = new MyObject;
const MyObject *o2 = o1;
o1->set(...); // Will work and will change the instance variables.
o2->set(...); // Won't compile.
Now, the const keyword can be used in three different contexts:
Assuring the caller of a method that you won't modify the object
For example:
void func(const MyObject &o);
void func(const MyObject *o);
In both cases, any modification made to the object will remain outside the function scope, that's why using the keyword const I assure the caller that I won't be modifying it's instance variables.
Assuring the compiler that a specific method do not mutate the object
If you have a class and some methods that "gets" or "obtains" information from the instance variables without modifying them, then I should be able to use them even if the const keyword is used. For example:
class MyObject
{
...
public:
void setValue(int);
int getValue() const; // The const at the end is the key
};
void funct(const MyObject &o)
{
int val = o.getValue(); // Will compile.
a.setValue(val); // Won't compile.
}
Finally, (your case) returning a const value
This means that the returned object cannot be modified or mutated directly. For example:
const MyObject func();
void func2()
{
int val = func()->getValue(); // Will compile.
func()->setValue(val); // Won't compile.
MyObject o1 = func(); // Won't compile.
MyObject o2 = const_cast<MyObject>(func()); // Will compile.
}
More information about the const keyword: C++ Faq Lite - Const Correctness
Regarding references
Returning or receiving a reference means that the object will not be duplicated. This means that any change made to the value itself will be reflected outside the function scope. For example:
void swap(int &x, int &y)
{
int z = x;
x = y;
y = z;
}
int a = 2; b = 3;
swap(a, b); // a IS THE SAME AS x inside the swap function
So, returning a reference value means that the value can be changed, for instance:
class Foo
{
public:
...
int &val() { return m_val; }
private:
int m_val;
};
Foo f;
f.val() = 4; // Will change m_val.
More information about references: C++ Faq Lite - Reference and value semantics
Now, answering your questions
const int exampleOne();
Means the object returned cannot change through the variable. It's more useful when returning objects.
int& exampleTwo();
Means the object returned is the same as the one inside the function and any change made to that object will be reflected inside the function.
const int& exampleThree();
Means the object returned is the same as the one inside the function and cannot be modified through that variable.
Never thought, that we can return a const value by reference and I don't see the value in doing so..
But, it makes sense if you try to pass a value to a function like this
void func(const int& a);
This has the advantage of telling the compiler to not make a copy of the variable a in memory (which is done when you pass an argument by value and not by reference). The const is here in order to avoid the variable a to be modified.

Passing references to pointers in C++

As far as I can tell, there's no reason I shouldn't be allowed to pass a reference to a pointer in C++. However, my attempts to do so are failing, and I have no idea why.
This is what I'm doing:
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
// sometime later
{
// ...
string s;
myfunc(&s);
// ...
}
And I'm getting this error:
cannot convert parameter 1 from 'std::string *' to 'std::string *&'
Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:
string s;
string* _s = &s;
myfunc(_s);
should compile just fine.
However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itself you should use a reference to the string as Sake suggested. With that in mind it should be more obvious why the compiler complains about you original code. In your code the pointer is created 'on the fly', modifying that pointer would have no consequence and that is not what is intended. The idea of a reference (vs. a pointer) is that a reference always points to an actual object.
The problem is that you're trying to bind a temporary to the reference, which C++ doesn't allow unless the reference is const.
So you can do one of either the following:
void myfunc(string*& val)
{
// Do stuff to the string pointer
}
void myfunc2(string* const& val)
{
// Do stuff to the string pointer
}
int main()
// sometime later
{
// ...
string s;
string* ps = &s;
myfunc( ps); // OK because ps is not a temporary
myfunc2( &s); // OK because the parameter is a const&
// ...
return 0;
}
Change it to:
std::string s;
std::string* pS = &s;
myfunc(pS);
EDIT:
This is called ref-to-pointer and you cannot pass temporary address as a reference to function. ( unless it is const reference).
Though, I have shown std::string* pS = &s; (pointer to a local variable), its typical usage would be :
when you want the callee to change the pointer itself, not the object to which it points. For example, a function that allocates memory and assigns the address of the memory block it allocated to its argument must take a reference to a pointer, or a pointer to pointer:
void myfunc(string*& val)
{
//val is valid even after function call
val = new std::string("Test");
}
&s produces temporary pointer to string and you can't make reference to temporary object.
Try:
void myfunc(string& val)
{
// Do stuff to the string pointer
}
// sometime later
{
// ...
string s;
myfunc(s);
// ...
}
or
void myfunc(string* val)
{
// Do stuff to the string pointer
}
// sometime later
{
// ...
string s;
myfunc(&s);
// ...
}
EDIT: I experimented some, and discovered thing are a bit subtler than I thought. Here's what I now think is an accurate answer.
&s is not an lvalue so you cannot create a reference to it unless the type of the reference is reference to const. So for example, you cannot do
string * &r = &s;
but you can do
string * const &r = &s;
If you put a similar declaration in the function header, it will work.
void myfunc(string * const &a) { ... }
There is another issue, namely, temporaries. The rule is that you can get a reference to a temporary only if it is const. So in this case one might argue that &s is a temporary, and so must be declared const in the function prototype. From a practical point of view it makes no difference in this case. (It's either an rvalue or a temporary. Either way, the same rule applies.) However, strictly speaking, I think it is not a temporary but an rvalue. I wonder if there is a way to distinguish between the two. (Perhaps it is simply defined that all temporaries are rvalues, and all non-lvalues are temporaries. I'm not an expert on the standard.)
That being said, your problem is probably at a higher level. Why do you want a reference to the address of s? If you want a reference to a pointer to s, you need to define a pointer as in
string *p = &s;
myfunc(p);
If you want a reference to s or a pointer to s, do the straightforward thing.
Welcome to C++11 and rvalue references:
#include <cassert>
#include <string>
using std::string;
void myfunc(string*&& val)
{
assert(&val);
assert(val);
assert(val->c_str());
// Do stuff to the string pointer
}
// sometime later
int main () {
// ...
string s;
myfunc(&s);
// ...
}
Now you have access to the value of the pointer (referred to by val), which is the address of the string.
You can modify the pointer, and no one will care. That is one aspect of what an rvalue is in the first place.
Be careful: The value of the pointer is only valid until myfunc() returns. At last, its a temporary.
I have just made use of a reference to a pointer to make all the pointers in a deleted binary tree except the root safe. To make the pointer safe we just have to set it to 0. I could not make the function that deletes the tree (keeping only the root) to accept a ref to a pointer since I am using the root (this pointer) as the first input to traverse left and right.
void BinTree::safe_tree(BinTree * &vertex ) {
if ( vertex!=0 ) { // base case
safe_tree(vertex->left); // left subtree.
safe_tree(vertex->right); // right subtree.
// delete vertex; // using this delete causes an error, since they were deleted on the fly using inorder_LVR. If inorder_LVR does not perform delete to the nodes, then, use delete vertex;
vertex=0; // making a safe pointer
}
} // end in
Bottom line, a reference to a pointer is invalid when the formal parameter is the (this) pointer.
I know that it's posible to pass references of pointers, I did it last week, but I can't remember what the syntax was, as your code looks correct to my brain right now. However another option is to use pointers of pointers:
Myfunc(String** s)
myfunc("string*& val") this itself doesn't make any sense. "string*& val" implies "string val",* and & cancels each other. Finally one can not pas string variable to a function("string val"). Only basic data types can be passed to a function, for other data types need to pass as pointer or reference.
You can have either string& val or string* val to a function.