Good day,
I'm trying new things in C++ and I found case where Debug and Release configurations in Visual Studio gave me a different results.
#include <experimental/generator>
#include <fstream>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
template <typename T = std::string>
auto getLineByLine(std::string filename, std::function<T(std::string&)> func = [](std::string& var) { return var; })
{
std::ifstream infile(filename);
std::string line;
while (getline(infile, line))
{
yield func(line);
}
}
int main()
{
std::vector<std::string> myVector;
for (const auto& line : getLineByLine("fileWithMoreThanOneLine.txt"))
{
myVector.push_back(line);
}
std::cout << myVector[0] << std::endl;
}
This code in Debug outputs as expected - one line from file fileWithMoreThanOneLine.txt.
But in Release it crashes on last line when I'm printing first string in vector.
When I tried to debug it I found that variable myVector was "optimized away and not available." in Release. I think this is not right optimization.
Also I found that if I change one line to this:
for (const auto& line : getLineByLine("fileWithMoreThanOneLine.txt", [&myVector](std::string& var) { return var; }))
it compiles correctly. But variable myVector is not needed in lambda function, right?
Is this problem with my code or MSVC compiler? I tried VS 2015 Update 1 (first VS with coroutines) and VS "15" with daily build of VC++.
Thank you,
Miroslav Hrnčíř
P.S. I'm sorry for my bad English and if it's dumb question.