Home > Net >  Creating a struct without a variable name, how is it useful?
Creating a struct without a variable name, how is it useful?

Time:09-17

I just came across this syntax and I am not sure where can I really make use of it.

std::hash<std::string>{}(str);

I see that no variable name was used here for reference to the record created and I would like to know why anyone would be using this syntax to create structs/record except for calling functions/overloaded operators?

CodePudding user response:

Essentially, yeah, you do that if you want to call a constructor or a member function, but you don't care about the object itself.

From my experience, this is most common with RAII types where the lifetime of the object is tied to the resource. You create an object, thereby acquiring a resource (like a file or sth), and then do something with that resource. Now say you don't need it afterwards. If you don't give it a name, it will call the destructor directly after you're done with it since the 'variable' (which doesn't even really exist) goes out of scope immediately, thereby freeing the resource.

  • Related