Advertisement
Geometrian

Understanding & and && returns

Aug 4th, 2015
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. //http://chat.stackoverflow.com/rooms/85059/discussion-between-imallett-and-matt-mcnabb
  2.  
  3. References are better thought of as "equivalent" names for things, not fancy pointers.
  4.  
  5. Semantics:
  6.  
  7. `Foo bar() { return Foo(); }`
  8. `Foo const c_bar() { return Foo(); }`
  9. Both functions contruct a new `Foo` in their stack space and then return it, copy/move-contructing a `Foo` in the caller's stack space (exactly how varies by the example below). Then, the callee's locally constructed return value is deleted and the stack popped back to the caller. Then, possibly some other (semantic) operations occur.
  10.  
  11. `Foo x = bar(); //example 1`
  12. `Foo const y = c_bar(); //example 2`
  13. `Foo const z = bar(); //example 3`
  14. `Foo w = c_bar(); //example 4`
  15. The return value copy/move-constructs a temporary on the caller's stack. The return value is then destructed. The temporary then copy/move-constructs `x`, `y`, `z`, or `w` respectively. The temporary is then destructed.
  16.  
  17. `Foo& x = bar(); //example 5`
  18. `Foo& w = c_bar(); //example 6`
  19. This syntax is illegal.
  20. `Foo const& y = c_bar(); //example 7`
  21. The return value is copy/move-constructed into a `const` <var> on the caller's stack. The return value is then destructed. The <var> is given the name `y`.
  22. `Foo const& z = bar(); //example 8`
  23. The return value is copy/move-constructed into a value <temp> on the caller's stack. The return value is then destructed. <temp> then copy/move-constructs <var>, which is `const`. <temp> is then destructed. <var> is given the name `z`.
  24.  
  25. `Foo&& x = bar(); //example 9`
  26. `Foo const&& y = c_bar(); //example 10`
  27. The return value is copy/move-constructed into a <var> on the caller's stack. The return value is then destructed. The <var> is then given the name `x` or `y`, respectively.
  28. `Foo const&& z = bar(); //example 11`
  29. Exactly the same as example 8.
  30. `Foo&& w = c_bar(); //example 12`
  31. This syntax is illegal.
  32.  
  33. However, in practice, in all of the above, RVO is applied where possible, and extraneous copies are elided. Optimistically, this forms the following (execution) equivalence classes for the given examples:
  34. 1, 9 //non-const initializing non-const
  35. 2, 7, 10 // const initializing const
  36. 3, 8, 11 //non-const initializing const
  37. 4 // const initializing non-const (by copy)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement