指向引用的指针获取器

Pointer getter to a reference

本文关键字:获取 指针 引用      更新时间:2023-10-16

我有一个带有引用的类,想要一个返回指针的 getter。

class X {
    std::string& text;
public:
    auto GetText() -> decltype(text) * { return &text); // doesn't work
    X(std::string& text): text(text) {}
};

简单的方法是传递指向此类的指针。但是,如果我传递一个引用,我可以获得一个带有 getter 的指针吗?

编辑:这是错误消息

error: cannot declare pointer to 'std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}'
auto GetText() -> decltype(text) * { return &text);
                                 ^

首先,

auto GetText() -> decltype(text) * { return &text); // doesn't work

是声明此签名的一种非常可恶的方式。喜欢

std::string* GetText(){ return &text);

甚至只是

auto GetText(){ return &text);

但这不是代码审查。

这里的问题是你要求一个指向text成员变量的声明类型的指针,该变量是一个字符串引用(std::string&(。从评论部分来看,您似乎没有意识到decltype尊重其论点的"参考性"、"恒定性"和"易失性"。

您不能在C++中具有指向引用的指针,例如 std::string&*格式不正确。调用 std::remove_reference_t 应该可以解决这个问题,例如

auto GetText() -> std::remove_reference_t<decltype(text)> * { return &text);

但是,在这种情况下,无论如何auto都会正确推断出您的类型,因此您的显式声明是不必要的。

我已经为我最初的问题制作了一个测试程序。该程序有一个带有指针的类和一个返回引用的 getter,以及一个带有引用的第二个类和一个返回指针的 getter。

而且似乎-> std::remove_reference_t<decltype(text)>可以用-> decltype(&text)代替.

随意发表评论。

// g++ main.cpp -o test_reference_pointer && strip -s test_reference_pointer && ./test_reference_pointer
#include <iostream>
// A class with a pointer and a getter that returns a reference.
class A {
    std::string *text;
public:
    std::string& GetText_old_way() { return *text; }
    auto GetText_pure_auto() { return *text; }
    auto GetText_pointer_arithmetic() -> decltype(*text) & { return *text; }
public:
    A(std::string *text): text(text) {}
};
// A class with a reference and a getter that returns a pointer.
class B {
    std::string& text;
public:
    std::string *GetText_old_way() { return &text; }
    auto GetText_pure_auto() { return &text; }
    auto GetText_pointer_arithmetic() -> decltype(&text) { return &text; }
    auto GetText_remove_reference() -> std::remove_reference_t<decltype(text)> * { return &text; }
public:
    B(std::string& text): text(text) {}
};
int main() {
    std::string text = "hello, world";
    {//TEST
        A a(&text);
        unsigned int i{0};
        std::cout << "-- Test 1:"<< std::endl;
        ++i; std::cout << i << ". " << a.GetText_old_way() << std::endl;
        ++i; std::cout << i << ". " << a.GetText_pointer_arithmetic() << std::endl;
        ++i; std::cout << i << ". " << a.GetText_pure_auto() << std::endl;
        std::cout << std::endl;
    }
    {//TEST
        B b(text);
        unsigned int i{0};
        std::cout << "-- Test 2:"<< std::endl;
        ++i; std::cout << i << ". " << *b.GetText_old_way() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_pointer_arithmetic() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_remove_reference() << std::endl;
        ++i; std::cout << i << ". " << *b.GetText_pure_auto() << std::endl;
        std::cout << std::endl;
    }
    return 0;
}