Return a pointer while initializing it? C++ - c++

I want to know if it's possible to return a pointer while initializing it. I know that we can use string s("Hi") to declare and initialize a string s, but can we do the same for a pointer?
What I'm trying to do is keep my code as minimal as possible to try to learn to optimize my code, so I tried queue<string> *p(&item) where item is a queue<string>. This works; however, adding return results in the error "Expected primary-expression before *".
My code snippet:
struct parsedObj
{
queue<string> item;
bool operator!() {return !item.empty();}
queue<string>* operator*() {return queue<string> *p(&item);}
};

I want to know if it's possible to return a pointer while initializing it
You always initialize the return value. There is no way to not initialize it. (Well, you could forget to write the return statement, but that makes the program ill-formed).
but can we do the same for a pointer?
Yes.
adding return results in the error "Expected primary-expression before *".
This limitation applies to non-pointers as well. You cannot write return string s("Hi") either for example.
The syntax of return statement is attr(optional) return expression(optional). A declaration is not an expression. string s("Hi") and queue<string> *p(&item) are declarations.
Simply use
return &item;
to return a pointer. There's no need to declare any variables in that function.
PS. It seems quite perverse to return a pointer to a member from the indirection operator. Conventionally the indirection operator does the opposite (i.e. the operand of the indirection is a pointer, and the result is the pointed object).

I used this instead and it did the job better than having a pointer:
queue<string>* operator->() {return &item;}
This is not the solution, this is just a tip. Now I can use parsedObj-> which simplifies the process.

Related

type without identifier parameter in a static void function

I saw code below the other day, (I have sanitized it because it was not open source/public) but dont understand how the type without identifier does anything/is used. I cannot find anything that clearly describes what is happening here seems like a pre-declaration thing or a prototyping thing but this was the actual function definition, can anyone explain, sorry if it is a newbie question.
static void myfunction(int /*comment*/)
{
// code here, loop that waits for a pid to exit
}
The argument isn't used in the function, and to avoid possible warnings about that one could omit the argument variable name.
Whatever value is passed when calling the function is simply ignored.
Since the C++17 standard you can also use the [[maybe_unused]] attribute to tell that an argument might not be used inside the function:
static void myfunction([[maybe_unused]] int argument)
{
// ...
}
This attribute can also be used for other variables, not only arguments, as well as for whole functions.
An unnamed int could be used as a placeholder for differentiating identical function signatures, a classical example could be to overload the post-increment and pre-increment operator:
//Define prefix increment operator
Point& Point::operator++()
{
_x++;
_y++;
return *this;
}
// Define postfix increment operator.
Point Point::operator++(int)
{
Point temp = *this;
++*this;
return temp;
}

Making overloaded member access operator in C++ return a temporary

I want to write class similar to below, where IteratorLike can only be dereferenced to a new value, as the iterator provides a view different to the underlying structure that makes returning a simple reference unfeasible.
class IteratorLike
{
public:
MyValue operator*() const { return MyValue(...); }
auto operator->() const { return **this; } // This does not work generally due to member access semantics.
};
All in all, I just want IteratorLike()->x to mean the same thing as (*IteratorLike()).x.
One could simply overload operator->() in the MyValue class, but i want this to work in all cases.
Using a wrapper type that overloads operator->() seemed like a plausible solution, but this does not work when returning an rvalue.
In the example on godbolt is a working implementation of such a wrapper, including the undefined behaviour it causes due to the dangling reference.
Is there a way to make this work?
If the wrapper could return a pointer to an prvalue, then the line int &qa = MyIteratorLike()->x; would in my understanding be caught by the compiler, but such a thing seems impossible.
Is there a way to make this work?
No. Value category is a property of an expression, not of a type. "pointer to prvalue" is not a thing

C++: Pointer to Member Function within Struct

This is a follow up question to my previous post: C++: Initializing Struct and Setting Function Pointer
My new question is how do I call a pointer-to-member function within a struct? I have modified my previous code to:
float MyClass::tester(float v){
return 2.0f*v;
}
struct MyClass::Example{
float(Scene_7::*MyFunc)(float);
float DoSomething(float a){
return (MyFunc)(a); //ERROR, SEE BELOW FOR OUTPUT
}
};
I then set the function as follows, and output the result to the call:
struct Example e;
e.MyFunc = &MyClass::tester;
std::cerr << e.DoSomething(1.0f) << std::endl;
I get the following error: must use '.' or '->' to call pointer-to-member function...
The problem is I don't know how to do this. I am guessing I have to call something like this->*(myFunc)(a) within DoSomething but this references the struct. I have tried searching "this within struct pointer-to-member function" but have not been able to find anything. Any help or suggestions would be great. I feel like I am close but it is just a matter of syntax at this point.
The operator precedence of .* and ->* is, IMHO, broken. You need to wrap the operands in parentheses in order to call.
return (this->*MyFunc)(a);
Otherwise, the compiler thinks you're doing this->*(MyFunc(a)), which is obviously invalid.
Interestingly enough, (this->*MyFunc) as a standalone expression is also invalid. It needs to be called on the spot.
I cant tell if you have other errors, do to the lack of code, but you are calling a member function the wrong way, you call them like this:
return (obj->*MyFunc)(6);
I am not sure if you can use this in place of obj on the line above, since from the declaration, you need a pointer to an object of type Scene_7, so you will need to know a pointer of the correct type at that spot in the code..
Remember that . operator has higher precedence than the * operator. So when dealing with pointes and structs etc you will need to use paranthesis or -> operator which means that the pointer points to what.

C++ Primer Plus this pointer example

Sorry for turning to here for such a basic question, but can someone just quickly clear this up for me? I'll then delete the thread so as not to cause noob clutter.
In the following example from the C++ Primer Plus text, doesn't the & operator in the function declaration designate that the function returns a pointer to a Stock object? Why then does the function proceed to return the s and this objects by value instead?
"...What you want to return, however, is not this, because this is the address of the object. You want to return the object itself, and that is symbolized by *this. (Recall that applying the dereferencing operator * to a pointer yields the value to which the pointer points.) Now you can complete the method definition by using *this as an alias for the invoking object."
const Stock & Stock::topval(const Stock & s) const {
if (s.total_val > total_val)
return s; // argument object
else
return *this; // invoking object
}
Yeah, that's confusing. C++ massively overloads every symbol, because there just aren't enough symbols on the keyboard.
The ampersand & is used for two different meanings which are conceptually similar, but are actually completely different language features.
Meaning 1: Reference type declaration. Append an ampersand to type A which means a-reference-to-type-A. Example:
Stock x;
Stock& s = x; // now s is a reference to x
Meaning 2: Address-of operator. A unary operator that returns a pointer to its argument. Example:
Stock x;
Stock* s = &x; // now s a pointer to x
Reminder: References and pointers are exactly the same thing, except they have different syntax, and references can never be null, and you can't have a reference to a reference.
Don't delete this thread, we love n00bs. I'm a n00b myself.
const Stock & means return a const reference to an object. A pointer to an object would be const Stock *. Don't mix the two! So the this pointer is being dereferenced and returned.

C++ pointer casting when passing pointer as parameter to reference

I'm curious, is:
bool State::operator<(const State* S)
{
return this->operator<(*dynamic_cast<const State *>(S));
}
exactly the same as:
bool State::operator<(const State* S)
{
return this->operator<(*(S));
}
For reference the this->operator< being called is:
bool State::operator<(const State& S)
{
return this->reward < S.reward ? true : false;
}
Which one is more "correct" and type safe / secure to use or, is there any actual difference ?
No, the first one casts the pointer to itself, which doesn't really do anything, and then calls const State* overload, which results in an infinite loop. You don't need dynamic_cast until you need to downcast at runtime — there is no downcasting here, so
return this->operator<(*S);
is the only thing to do.
Assuming you have a typo and you mean to compare this:
*dynamic_cast<const State *>(s)
...to this:
*s
...where s has compile-time type const State *, there is no difference at all.
It is conceivable that the former could be slightly slower if your compiler does not notice that they are compile-time equivalent.
I would avoid the former on the grounds that anybody reading it will wonder what you are thinking.