0

In some Boost ASIO example, I found the line auto self(shared_from_this());. self doesn't seem to be declared anywhere and doesn't seem to be a reserved keyword. In another example, I also found the use of auto self = shared_from_this();, which seems to be somehow equivalent. Why can I call something that is not declared before? And why does it somehow work as a variable declaration?

user3840170
  • 26,597
  • 4
  • 30
  • 62
medihack
  • 16,045
  • 21
  • 90
  • 134
  • 4
    https://en.cppreference.com/w/cpp/language/direct_initialization – Sebastian Redl Apr 06 '23 at 08:08
  • 1
    *"`self` doesn't seem to be declared anywhere"* -- Are you sure? You did not present much code, but even so I see a declaration of `self`, specifically the line `auto self(shared_from_this());`. Are you familiar with what the `auto` keyword means? Maybe that is what you should ask about. Or is it the parentheses that are throwing you off? Something else? It's tough to guess these things. – JaMiT Apr 06 '23 at 08:11
  • 2
    It works as a variable declaration because that's what it is. `int m = 5;` is a variable declaration. `int m(5);` is another one. `auto m = 5;` is another one. `auto m(5);` is another one. – n. m. could be an AI Apr 06 '23 at 08:17
  • @JaMiT From other languages, I am not used to call something that is not defined previously. But Sebastian is right, I was not aware of the direct initialization concept. – medihack Apr 06 '23 at 08:18
  • 1
    Well, you are calling the *constructor* (that should be already defined) of that object. Which type is deduced by `auto`. – Bob__ Apr 06 '23 at 08:21
  • See dupe [how does `A a2(A_factory_func());` work](https://stackoverflow.com/questions/1051379/is-there-a-difference-between-copy-initialization-and-direct-initialization) – Jason Apr 06 '23 at 09:43
  • @medihack *"I am not used to call something that is not defined previously."* -- And you still have not done so. Which leads to an observation: you wrote your question as if everyone sees the same thing you do. You did not explain what you thought was being called. You went from observations to conclusions without guiding your readers through the thought process. This is fine as long as everyone sees the same thing you do, but if that was the case, why was the code written that way? When your conclusions do not make sense to you, watch the assumptions and be more precise than "something". – JaMiT Apr 07 '23 at 09:30
  • @JaMiT You are right, but the comments here helped me to understand it (direct initialization in my case). And hopefully someone else in the future, too. – medihack Apr 07 '23 at 15:13

0 Answers0