Why

#include <string> #include <fstream> void touch(const std::string& name) { if (!name.empty()) std::ofstream f(name); } void main() { touch("foo"); } 

creates the file "foo" if it did not exist, but

 #include <string> #include <fstream> void touch(const std::string& name) { if (!name.empty()) std::ofstream(name); } void main() { touch("foo"); } 

does not create?

(Visual Studio 2015 Update 2)

  • The file is created, G ++ 6.1.1. Specify the version of the compiler and attach an assembler listing for both cases. - awesoon
  • Cited incomplete code, updated. Well, I already understand why the difference is in principle. - Vladimir Gamalyan
  • @VladimirGamalian, can you explain? - awesoon
  • @VladimirGamalian, please add to the post MCVE (for each of the cases), so that they can be simply taken and compiled, without thinking up the rest of the environment - awesoon
  • @soon As far as I understand, in the second case, a local variable name with the type std::ofstream with a constructor without parameters. - Vladimir Gamalyan

1 answer 1

Based on clause 8.3 / 6 of the Standard:

In the declaration TD where D has the form

(D1)

the declaration of the declaration of the declaration

T d1

We std::ofstream(name); that the entry std::ofstream(name); equivalent to std::ofstream name; Those. creating a variable of type std::ofstream with the name name default constructor, which, of course, does not create any files.

Actually it would become more obvious if you remove the touch function and leave the call to std::ofstream(name); straight into main . Well, IntelliSense could help in determining that the name inside if already has a different type ( std::ofstream ), and not std::string .

  • Interestingly, for example, like this: bool exist(const std::string& name) { !!std::ifstream(name);} a file opens with the name name - Vladimir Gamalyan
  • @VladimirGamalian is no longer a declaration. - 伪位蔚蠂慰位蠀蟿
  • Can be more. This is: std::ofstream(name); a declaration is obtained, and this is std::ifstream(name); not? - Vladimir Gamalyan
  • Rather, return or !! do not allow to be a declaration of this std::ifstream(name); ? - Vladimir Gamalyan
  • @VladimirGamalian essence available! before the type, therefore not a declaration. - 伪位蔚蠂慰位蠀蟿