0

I want to create a list of empty files from a list of paths:

#include <fstream>
#include <string>
#include <vector>

int main()
{
  std::vector<std::string> paths{ "foo.txt", "bar.txt", "baz.txt" };

  for (auto & path : paths)
  {
    std::ofstream new_file{ path, std::ofstream::trunc };
  }
}

This works, but the release of my code is compiled with the highest level of optimization. So my question is: is it a guarantee that my files will be created? I am afraid that some compilers “see” that this variable is unused and do not consider this line, although the constructor has a desired side effect.

Boiethios
  • 38,438
  • 19
  • 134
  • 183
  • 1
    The constructor creates the files (which is a huge side-effect), so the compiler is not going to remove that side-effect. – Nawaz Dec 22 '16 at 15:14
  • Is it guaranteed? – Boiethios Dec 22 '16 at 15:15
  • 1
    Boiethios, Yes. There is no optimization possible that would prevent the compiler from producing this side effect. It is like asking : would the compiler optimize `std::cout << "Hi"` and does nothing? – Nawaz Dec 22 '16 at 15:17
  • @LogicStuff That is not a dup, I don't speak about *as-if*, I do not even know this word. – Boiethios Dec 22 '16 at 15:18
  • 3
    You should read the "as-if".. that should answer your query. – Nawaz Dec 22 '16 at 15:18
  • @Nawaz Hum, that answer my question, thanks. But definitely not a dup: my question is about a concrete thing, not directly about a general behavior of C++ compilers – Boiethios Dec 22 '16 at 15:22
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/131264/discussion-between-boiethios-and-nawaz). – Boiethios Dec 22 '16 at 15:31

0 Answers0