0

I'm new to C++ and I'm reading this tutorial. I found the following code snippet.

X&& goo(); // (1)
X x = goo(); // (2)

I think X is a class name, but I don't understand what X&& goo(); does. I suppose there are two possibilities:

  1. It declares a function goo which returns a rvalue reference to X.
  2. It declares a variable goo and calls the default constructor (without arguments) of X.

But if 1 is true then since there is no function body how can it be called? And if 2 is true then what does line (2) do?

I tried to search for this syntax but wasn't able to figure out the correct keywords. Can anyone give a hint? Thanks!

Patrick
  • 555
  • 1
  • 6
  • 25
  • All the *compiler* need to know to be able to call a function is to know that the function exists *somewhere*. It's then the *linker* which checks that the functions actually exists (are defined). – Some programmer dude Sep 12 '21 at 06:13
  • And yes, `X&& goo();` is a function declaration. It declares a function named `goo` which takes no arguments and an rvalue reference to an `X` object. – Some programmer dude Sep 12 '21 at 06:14
  • It seems like it's a bit early for you to worry about rvalue references. Start with the basics in a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Sep 12 '21 at 08:48
  • Thomas Becker is a good C++ writer. He writes about specific aspects of C++, especially back when those were novel introductions to the language. What you are reading is am explanatory article to those novel aspects, not a tutorial to C++. I recommend you consider learning C++ from a [good C++ book](https://stackoverflow.com/a/388282/4641116) rather than narrowly focused article exploring a novel feature somewhat in isolation. – Eljay Sep 12 '21 at 12:23
  • Thanks for the answer and book recommendations! – Patrick Sep 12 '21 at 17:16

1 Answers1

0

is X&& goo(); a function declaration or a variable definition?

It is not a variable definition. If X is a type name, then it is a function declaration. If X is a variable and goo is callable, then it is an expression statement.

But if 1 is true then since there is no function body how can it be called?

It can be called using the function call expression: goo().

The definition of the function contains the body. If the function is odr-used (calling the function is an example of odr-use), then the function must be defined somewhere else. If it isn't defined anywhere, then the program is ill-formed (with no diagnostic required).

eerorika
  • 232,697
  • 12
  • 197
  • 326