Making l-value from r-value - c++

I've got quite a nifty get fnc which returns pointer to 'a type'. Now I would like to reuse this fnc in fnc set to set some value to this type returned by get:
template<class Tag,class Type>
set(Type t, some_value)
{
get<Tag>(t) = value;
}
The only problem I have is that: Because get returns pointer and not reference to a pointer the return type is a rvalue which for most cases is fine but not for this. Is there a way to somehow change the returned value into lvalue?

You can simply use this:
*get<Tag>(t) = value;
The result of dereferencing a pointer is an l-value.

Dereferencing a pointer (with the * operator) yields a reference. The type of the reference depends on the type of the pointer. const T * becomes const T &, while T * becomes T &.
So, if get returns a pointer to a non-const variable, you can write:
*get<Tag>(t) = value;
If get does not meet such requirement, and you can't change it, you'll have to give a set method instead.

Related

Why do we return *this in asignment operator and generally (and not &this) when we want to return a reference to the object?

I'm learning C++ and pointers and I thought I understood pointers until I saw this.
On one side the asterix(*) operator is dereferecing, which means it returns the value in the address the value is pointing to, and that the ampersand (&) operator is the opposite, and returns the address of where the value is stored in memory.
Reading now about assignment overloading, it says "we return *this because we want to return a reference to the object". Though from what I read *this actually returns the value of this, and actually &this logically should be returned if we want to return a reference to the object.
How does this add up? I guess I'm missing something here because I didn't find this question asked elsewhere, but the explanation seems like the complete opposite of what should be, regarding the logic of * to dereference, & get a reference.
For example here:
struct A {
A& operator=(const A&) {
cout << "A::operator=(const A&)" << endl;
return *this;
}
};
this is a pointer that keeps the address of the current object. So dereferencing the pointer like *this you will get the lvalue of the current object itself. And the return type of the copy assignment operator of the presented class is A&. So returning the expression *this you are returning a reference to the current object.
According to the C++ 17 Standard (8.1.2 This)
1 The keyword this names a pointer to the object for which a
non-static member function (12.2.2.1) is invoked or a non-static data
member’s initializer (12.2) is evaluated.
Consider the following code snippet as an simplified example.
int x = 10;
int *this_x = &x;
Now to return a reference to the object you need to use the expression *this_x as for example
std::cout << *this_x << '\n';
& has multiple meanings depending on the context. In C and used alone, I can either be a bitwise AND operator or the address of something referenced by a symbol.
In C++, after a type name, it also means that what follows is a reference to an object of this type.
This means that is you enter :
int a = 0;
int & b = a;
… b will become de facto an alias of a.
In your example, operator= is made to return an object of type A (not a pointer onto it). This will be seen this way by uppers functions, but what will actually be returned is an existing object, more specifically the instance of the class of which this member function has been called.
Yes, *this is (the value of?) the current object. But the pointer to the current object is this, not &this.
&this, if it was legal, would be a pointer-to-pointer to the current object. But it's illegal, since this (the pointer itself) is a temporary object, and you can't take addresses of those with &.
It would make more sense to ask why we don't do return this;.
The answer is: forming a pointer requires &, but forming a reference doesn't. Compare:
int x = 42;
int *ptr = &x;
int &ref = x;
So, similarly:
int *f1() return {return &x;}
int &f1() return {return x;}
A simple mnemonic you can use is that the * and & operators match the type syntax of the thing you're converting from, not the thing you're converting to:
* converts a foo* to a foo&
& converts a foo& to a foo*
In expressions, there's no meaningful difference between foo and foo&, so I could have said that * converts foo* to foo, but the version above is easier to remember.
C++ inherited its type syntax from C, and C type syntax named types after the expression syntax for using them, not the syntax for creating them. Arrays are written foo x[...] because you use them by accessing an element, and pointers are written foo *x because you use them by dereferencing them. Pointers to arrays are written foo (*x)[...] because you use them by dereferencing them and then accessing an element, while arrays of pointers are written foo *x[...] because you use them by accessing an element and then dereferencing it. People don't like the syntax, but it's consistent.
References were added later, and break the consistency, because there isn't any syntax for using a reference that differs from using the referenced object "directly". As a result, you shouldn't try to make sense of the type syntax for references. It just is.
The reason this is a pointer is also purely historical: this was added to C++ before references were. But since it is a pointer, and you need a reference, you have to use * to get rid of the *.

"expression must be an l-value or function designator" error when taking the address of this

I'm trying to do this in C++:
class Abc
{
int callFunction1()
};
void function1(Abc** c1) {//do something}
int Abc::callFunction1()
{
function1(&this);
return 0;
}
And I get "expression must be an l-value or function designator" error in visual studio 2015. So I don't understand where I go wrong. To my knowledge, &this should have the type Abc** right?
The function definition isn't mine to change. So I can't just change the parameter type.
The error is clear enough. Since this is not an lvalue, you cannot take its address. If you just want the address of the object, then just pass this, not &this, and change the function declaration to:
void function1(Abc* c1) //To just pass a pointer
However, since you mentioned you cannot change the definition of the function, you can create a temporary variable and pass its address:
auto temp = this;
function1(&temp);
How this works:
Since this is a prvalue and cannot have its address taken, you need something to point to it to turn it into an lvalue, here temp.
Now that temp points to this, taking temp's address will effectively take this's address, albeit indirectly.
Therefore, since you are passing the address of an lvalue to function1, the code compiles and works as expected.
From the C++ Standard (9.2.2.1 The this pointer)
1 In the body of a non-static (9.2.1) member function, the keyword
this is a prvalue expression whose value is the address of the
object for which the function is called.
and (5.3.1 Unary operators)
3 The result of the unary & operator is a pointer to its operand. The
operand shall be an lvalue or a qualified-id....
To make it more clear consider the following code snippet.
If for example you have a declaration
int x = 10;
then you may not write
int **p = &&x;
In the right expression &x is a prvalue and according to the second quote from the Standard you may not apply the unary operator & to the prvalue.
You could write
int *q = &x;
int **p = &q;
because q is lvalue.
The expression this is an rvalue, the same way that the expressions 137 or 'a' are, and so you can't take its address.
If you want to get a pointer to a pointer to this, you'll need to create a new variable of the right type:
auto* ptr = this;
doSomething(&ptr);

Not understanding C++ type mismatch: const Foo* to Foo* const&

Having this set of objects and statements:
QSet<Foo*> set;
iterator QSet::insert(const T & value) //type of the function I want to call
const Foo * get() const //type of the function I use to get the argument
set.insert(get()); //the line showing up as error
I get the error "no known conversion for argument 1 from 'const Foo*' to 'Foo* const&". I guess I have trouble reading these types because I have no idea what I should do to make this work.
From what I've read, the const keyword applies to the type to its left with the exception of a top-level const which can be written to the left of the type it applies to. My guess would be that I have to convert get() to a reference but I'm unsure how to do that.
There seem to be a couple of misunderstandings here (both by the questioner and by some answers).
First, you said "My guess would be that I have to convert get() to a reference but I'm unsure how to do that". Let's try clearing this up:
1) "I have to convert get() to a reference" -- Actually, you don't!
iterator QSet::insert(const T & value) does indeed take a reference. But it's a reference to type T. So the question is, "what is type T"?
In this case, T=Foo *. So insert, in this instance of the template, is actually:
iterator QSet::insert(Foo * const & value) -- read it from right to left: insert takes a reference to a constant pointer to a Foo.
2) "I'm unsure how to do that [convert a pointer to a reference]" -- while you don't have to do it here, in general you do this by de-referencing the result of get. For example: *(get()).
Second, the compiler error. The error arises because there is a conflict:
a) get() returns a const Foo *
b) but set stores a Foo* -- NOT a const Foo *, so insert only accepts a changeable Foo
So you can't store a constant pointer inside your QSet<Foo*>. This makes sense because you can use set to access and change the Foos inside it, which you promise not to do with a const Foo.
This reference should be helpful:
https://isocpp.org/wiki/faq/const-correctness
You may also think whether you can just use a QSet<Foo> instead of a QSet<Foo*>. In the former case, things will probably behave how you expect.
You are trying to take a const Foo * and insert it into a QSet<Foo *>, but the compiler won't automatically convert a const Foo * to a plain Foo * in order to do so.
I solved the problem by changing the type of the set as follows.
QSet<Foo const*> set;
With this change, compilation succeeds.
You're violating the const-ness of the pointer returned from your get() function. get() returns a pointer to a const object of type Foo, but then you try to insert it into a vector of non-const Foo pointers. You need to const_cast the return value from get() or change the return type of get() from const Foo* to just Foo*.

Regarding definition of dereferencing and member selection operators in smart pointer

In smart pointer implementation, dereferencing operator and member selection operators are always defined as below.
T& operator* () const // dereferencing operator
{
return *(m_pRawPointer);
}
T* operator->() const // member selection operator
{
return m_pRowPointer;
}
I don't quite understand why the former is returned by reference, the latter is returned by pointer. Is it just to differentiate them or some other reasons?
To be more specific, can I make dereferencing operator returns by pointer, while the other one returns by reference?
why the former is returned by reference
So that the expression *thing gives an lvalue denoting an object of type T, just as it would if thing were a pointer.
the latter is returned by pointer
Because that's how the language is specified. Note that you never use the result of -> directly, but always in an expression of the form thing->member.
If thing is a class type, that's evaluated by calling operator->, then applying ->member to the result of that. To support that, it must return either a pointer, or another class type which also overloads operator->.
can I make dereferencing operator returns by pointer
Yes, but that would be rather confusing since it would behave differently to applying the same operator a pointer. You'd have to say **thing to access the T.
while the other one returns by reference
No, because that would break the language's built-in assumptions about how the overloaded operator should work, making it unusable.
The reason that the dereference operator returns by reference and the member selection operator returns by pointer is to line up the syntax of using a smart pointer with the syntax of using a raw pointer:
int* p = new int(42);
*p = 7;
std::unique_ptr<int> p(new int(42));
*p = 7;
You could absolutely make your dereference operator return anything you like:
struct IntPtr {
int* p;
int* operator*() { return p; }
};
But that would be pretty confusing for your users when they have to write:
IntPtr p{new int{42}};
**p = 7;
The arrow operator is a little different in that [over.ref]:
An expression x->m is interpreted as (x.operator->())->m
So you have to return something on which you can call ->m, otherwise you'll just get an error like (from gcc):
error: result of 'operator->()' yields non-pointer result

how *return implicitly return a reference

this is a const ptr to the object/instance which a member function receive implicitly, so how does return *this returns a reference ?
As of what I know , a pointer dereferencing to a variable means it holds it's memory address , so return *this should return value dereferenced by this const pointer which is what? An object?
Also, why you can't do something like this:
Calc cCalc;
cCalc.Add(5).Sub(3).Mult(4);
Without having all that member functions to return *this?
I would want to know how pointers and reference treat objects/instances.
Let's try to untangle:
this is a const ptr to the object/instance which a member function receive implicitly
member functions indeed receive this pointer implicitly. The type is T* or const T* depending on the member function signature -- you get const placing const keyword at the tail after the ().
so how does return *this returns a reference ?
*this dereference the pointer, thus creating lvalue of type T or const T respectively. If your question is meant how you get T& from *this in a const funstion, the answer that you don't, that attempt would be ill-formed code.
As of what I know , a pointer dereferencing to a variable means it holds it's memory address , so return *this should return value dereferenced by this const pointer which is what? An object?
*this denotes the instance. And it is lvalue expression. So you can get its address agan (providing same as this), or can bind it to a reference -- including the case for a return.
The chaining you show can actually be done if the functions returned Calc instead of Calc& or returned some different object than *this -- but then the result of calculations would end up in that place. Not where you expect it: in cCalc.
As it stands, when all three functions return *this leads first Add taking &cCalc in this, and returns cCalc. The next call to Sub has the same situation. And Multiply too.
Add member doesnt have Sub function. Compiler give an error.
But, if you return *this, you are returning your own object (not reference). Now you have one cCalc object that can use Sub(3). Sub(3) return your object and can use Mult(4).