关于R值

发布于 2025-01-16 04:18:09 字数 739 浏览 2 评论 0原文

#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;
} 

在上述情况下,为什么调用函数 print_name 而不是 print_name_2 ?即使传递的是 R 值?我还想知道,引用常量 R 值的目的是什么。

#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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

东京女 2025-01-23 04:18:09

您的意思是 print_nameprint_name_2 是同一函数的重载吗?无论传递什么参数,编写 print_name 都不会调用 print_name_2

将两个函数更改为具有相同的名称将导致按预期调用右值版本: 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);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文