-1
#include <iostream>
#include <ctime>
#include <chrono>
#include "Person.h"
#include "SmartPerson.h"
using namespace std;

void print_name(const Person& test);
void print_name_2(const Person&& test);

int main()
{
    print_name(Person{ 21, "Juan", "Hispanic" });

    return 0;
}

void print_name(const Person& test)
{
    cout << "L value!" << endl;
    cout << test.get_name() << endl;
}
void print_name_2(const Person&& test)
{
    cout << "R value!" << endl;
    cout << test.get_name() << endl;
} 

Why is the function print_name called instead of print_name_2 in the above case? Even though it was an R-value being passed? I also want to know, what the purpose of a reference to a constant R-value is.

balu
  • 1,023
  • 12
  • 18
Brad
  • 17
  • 6

1 Answers1

2

Did you mean for print_name and print_name_2 to be overloads of the same function? Writing print_name will never invoke print_name_2 no matter the arguments that are passed.

Changing both functions to have the same name will cause the rvalue version to be called as expected: https://godbolt.org/z/PdvEe768z.

#include <iostream>

struct Person {};
using namespace std;

void print_name(const Person& test);
void print_name(const Person&& test);

int main()
{
    print_name(Person{});

    return 0;
}

void print_name(const Person& test)
{
    cout << "L value!" << endl;
}
void print_name(const Person&& test)
{
    cout << "R value!" << endl;
    Person a = std::move(test);
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • What is precedence of function-overloads if both`const &` and `const &&` exits ? [DEMO](https://onlinegdb.com/qq8-ezSHC) – TruthSeeker Mar 21 '22 at 08:25
  • Yes, I meant that, I was too focused and did not notice, my apologies. But I am still confused about the purpose of reference to constant R-value. – Brad Mar 21 '22 at 08:57
  • 1
    @TruthSeeker const& takes priority so that comparability will be maintained for old classes that have only copy constructors . – balu Mar 21 '22 at 08:57