c++ 为什么这个右值引用只对int有效而对structs无效[duplicate]

mmvthczy  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(168)

此问题在此处已有答案

Why does this compiler warning only show for int but not for string? "type qualifiers ignored on function return type"(4个答案)
Why is returning a const from a function not being detected as a const? [duplicate](2个答案)
4天前关闭.

  1. #include <iostream>
  2. //option 1
  3. struct Obj
  4. {
  5. auto f(int&& x) { printf("&&\n"); }
  6. auto f(int const& x) { printf("const&\n"); }
  7. auto g() const { return int{}; }
  8. const auto h() const { return int{}; }
  9. };
  10. //option 2
  11. struct Obj2
  12. {
  13. auto f(Obj&& x) { printf("&&\n"); }
  14. auto f(Obj const& x) { printf("const&\n"); }
  15. auto g() const { return Obj{}; }
  16. const auto h() const { return Obj{}; }
  17. };
  18. int main()
  19. {
  20. {
  21. int x;
  22. Obj obj;
  23. obj.f(obj.g()); // prints "&&"
  24. obj.f(obj.h()); // prints "&&"
  25. }
  26. printf("\n");
  27. {
  28. Obj x;
  29. Obj2 obj;
  30. obj.f(obj.g()); // prints "&&"
  31. obj.f(obj.h()); // doesn't print "&&" ?! Why?
  32. }
  33. }

据我所知,如果你从函数的返回值设置一个值,函数的返回值将是一个右值。

  1. auto x = foo(y); // x always receives an rvalue, right?


在上面的代码中,显然这并不总是发生。如果y是一个int它工作(选项1),但如果y是一个结构,g的返回值仍然是一个右值,但不是h。为什么?为什么它对int有效而不是对结构?

我正在使用C++20和GCC13.2

8cdiaqws

8cdiaqws1#

第一个月
如果一个纯右值最初的类型是“cv T”,其中T是一个cv限定的非类、非数组类型,那么在进行任何进一步的分析之前,表达式的类型会被调整为T。
换句话说,如果你通过值返回const T,而T既不是类也不是数组,那么const将被悄悄删除。
当你有一个const右值时,它不能绑定到一个非const T &&,但可以绑定到const T &,这样就可以使用重载。(一个非const右值可以绑定到T &&const T &,前者优先。)
因此,通过常量返回几乎总是一个错误,因为它阻止了你移动对象,默默地强制复制。在C++98中,它被用来阻止人们赋值给右值(而移动语义并不是一个东西),但现在你可以通过&来实现同样的效果-限定赋值运算符。

相关问题