首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用例表示`&‘ref-限定符?

用例表示`&‘ref-限定符?
EN

Stack Overflow用户
提问于 2022-04-12 15:03:19
回答 1查看 97关注 0票数 -1

我刚刚发现这是有效的C++:

代码语言:javascript
复制
struct S { 
  int f() &;         // !
  int g() const &;   // !!
}; 

int main() {
    S s;
    s.f();
    s.g();
}

this通过引用传递给f,通过const-reference传递到g .

这对任何人都有用吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-12 17:15:16

它们对于提供安全和优化都很有用。

对于返回指向它们所拥有的东西的指针的成员函数(直接或通过视图类型(如std::string_viewstd::span) ),禁用rvalue重载可以防止错误:

代码语言:javascript
复制
struct foo {
    int* take_ptr_bad() { return &x; }
    int* take_ptr() & { return &x; }
    int x;
};

foo get_foo();

void bar() {
    auto ptr = get_foo().take_ptr_bad();
    // ptr is dangling
    auto ptr = get_foo().take_ptr();
    // does not compile
}

另一种是提供一些优化。例如,如果this是一个rvalue以防止不必要的副本,您可能会重载一个getter函数返回一个rvalue引用:

代码语言:javascript
复制
struct foo {
    const std::string& get_str() const & {
        return s;
    }
    
    std::string&& get_str() && {
        return std::move(s);
    }
    
    std::string s;
};

void sink(std::string);

foo get_foo();

void bar() {
    sink(get_foo().get_str()); 
    // moves the string only if the r-value overload is provided.
    // otherwise a copy has to be made, even though the foo object
    // and transitively the string is temporary.
}

这就是我使用这个特性的方式,我相信还有更多的用例。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71844996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档