const reference

I trying to udnerstand const reference. In the code below does it mean that what is being returned by get() is not the copy of x (a copy of x like in pass by value) but a reference to x, which is a const, so it can not be changed?

1
2
3
4
5
6
 class MyClass {
  public:
    int x;
    MyClass(int val) : x(val) {}
    const int& get() {return x;} 
};
Yes.
1
2
3
MyClass answer( 42 );
std::cout << answer.get(); // essentially: cout << answer.x
answer.get() = 7; // error: assignment to const 

If the type of MyClass.x were something big, like vector, then the reference would have some advantage over copy.

Note that the caller can still make a copy from it:
1
2
int other = answer.get();
other = 7; // answer.x is still 42 
then the reference would have some advantage over copy.


but bear in mind modern copy elision and move semantics for returning a value from a function.
modern copy elision and move semantics for returning a value from a function.

Does that apply to member variables?
Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <vector>
#include <initializer_list>
#include <iostream>

class Mys {
	std::vector<int> vi;

public:
	Mys(const std::initializer_list<int>& li) : vi(li) {}
	auto get() const { std::cout << vi.data() << '\n';  return vi; }
};

int main()
{
	Mys s {1, 2, 3, 4, 5};

	auto v {s.get()};

	std::cout << v.data() << '\n';
}


which on my computer displays:


000000000019B920
000000000019B9C0


which shows that copying has taken place.
Last edited on
Copy elision is never applied on members (unless a clever optimiser exploits the as-if rule).
Move from a member is possible if we explicitly write code to support move semantics.

A trivial example:
1
2
3
4
5
6
7
struct foo
{
    const std::string& name() const & noexcept { return name_ ; }
    std::string name() && noexcept { return std::move(name_) ; } // called on rvalues

    std::string name_ ;
};

> which shows that no copying has taken place.

It shows that copying of the vector has definitely taken place.
My bad. I read 9C0 as 920. My eyesight! You replied before I had the chance to delete it.

Previous post changed.

Topic archived. No new replies allowed.