lvalue rvalue returns.

Cam I write a member method called Dereference

which will do both these

s.Dereference() -> prints the value of the variable.
s.Dereference()=4.9 -> sets the value of the variable.


What should be return type of the member method of that struct which has a
doube *p as the member.

Can a return type be both lvaue and rvalue?
What should be return type of the member method of that struct which has a
double *p as the member

That would be lvalue reference to double, the type double&.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cassert>

struct a 
{
  double* px; 
  double& dereference() const { assert(px); return *px; }
}; 

int main()
{
  double x;
  a my_a {&x};
  my_a.dereference() = 42.0;

  std::cout << x << '\n';
}


Can a return type be both lvalue and rvalue?

"lvalue" does not mean "goes on left of the assignment operator" and "rvalue" does not mean "goes on right of the assignment operator". C++ uses a more nuanced definition.

The terms "lvalue" and "rvalue" are classes of expressions, not types. Therefore one major conceptual problem with this question is that a type does not have a value category at all.

See this post:
https://www.cplusplus.com/forum/general/273175/#msg1178146
Last edited on
> Can a return type be both lvaue and rvalue?

A class member function can be overloaded on the ref-qualifier.
https://en.cppreference.com/w/cpp/language/member_functions#ref-qualified_member_functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>

struct A
{
    explicit A( std::string name ) noexcept : name_( std::move(name) ) {}

    std::string& name() & noexcept { return name_ ; } // lvalue reference to non-const

    const std::string& name() const & noexcept { return name_ ; } // lvalue reference to const

    std::string&& name() && noexcept { return std::move(name_) ; } // rvalue reference to non-const

    // though rvalue references to const are not particularly useful, they are part of the type system.
    // see: https://cplusplus.github.io/LWG/issue2485
    const std::string&& name() const && noexcept { return std::move(name_) ; } // rvalue reference to const

    private: std::string name_ ;
};
Thank you...
Topic archived. No new replies allowed.