I am a tiny bit confused regarding the following code, as it behaves differently using g++ -O3 and g++ -O1.
#include <iostream>
#include <set>
#include <fstream>
#include <string>
#include <map>
#include <sstream>
int main(int argc, char** argv){
if(argc<=1){
std::cerr << "No Input File... Abort" << std::endl;
return 1;
}
std::ifstream in_file;
in_file.open(argv[1]);
if(!in_file) {
std::cerr << "Input \"" << argv[1] << "\" Could not be opened!... Abort" << std::endl;
return 1;
}
std::map<
std::pair<int,int> /*position,level*/ ,
int
> triangle;
int level=0; //Counter of current depth in the triangle
while(!in_file.eof()){
std::string line;
std::getline(in_file, line); //Read in complete line (level of triangle)
std::cout << line << std::endl; //Print what he read
std::istringstream iss (line); //Split line into pieces
for(int position=-level;position<=level;position+=2){ //Move through one level of the triangle
int value;
iss >> value;
std::pair<int,int> current_position(position,level); //Position in triangle
triangle.emplace(current_position, value); //Erzeugung des Punktes und Speicherung des Pointers in der Map
}
level++;
}
// Print out map contents
for(int i=0;i<level;++i){
for(int position=-i;position<=i;position+=2){
std::pair<int,int> current_position(position,i);
std::cout << triangle.at(current_position) << " ";
}
std::cout << std::endl;
}
return 0;
}
This minimal example shall only read in a text-file of e.g. the following type with an empty line at the end:
1
2 3
I understand that if the file has an empty line at the end the stringstream in the loop will be empty and thus stream garbage. However, I do not understand why the behavior is different if I use -O3 or -O1:
g++ test.cpp -Wall -pthread -pedantic -Wextra -O1 -std=c++11 -o test
./test test_file
1
2 3
1
2 3
3 3 3
g++ test.cpp -Wall -pthread -pedantic -Wextra -O3 -std=c++11 -o test
./test test_file
1
2 3
1
2 3
0 0 0
This was tested on my system with: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.10)
As you can see, it seems like the -O3 compiled version leads to the stream forgetting its last input whereas the -O1 compiled version seems to store the value 3 which was last read in although it should be destroyed in the next loop iteration.