To enable me to read a binary file I have made this class. I would like to not copy a temporary for which I am trying to use move semantics. But this code produces "access violation error".
#include <fstream>
#include <iostream>
class myClass
{
public:
std::istream& myStream;
static myClass create(const char* path);
myClass(myClass&&) noexcept = default;
myClass(std::istream& input);
myClass() = default;
};
myClass myClass::create(const char* path)
{
std::ifstream input{ path, std::ios::binary | std::ios::in };
if (!input.is_open()) throw std::runtime_error("Error - couldn't open file");
return std::move(myClass(input));
}
myClass::myClass(std::istream& input) :
myStream(input)
{
}
int main()
{
const char* path = R"(file.bin)";
myClass cr{myClass::create(path)};
for (int i = 0; i < 10; i)
cr.myStream.seekg(i);
return 0;
}
CodePudding user response:
You are accessing the stream after the temporary has been destroyed. You need to store the stream in the myClass object:
#include <fstream>
#include <iostream>
class myClass
{
public:
std::istream& myStream;
static myClass create(const char* path);
myClass(myClass&& other) noexcept;
myClass(std::istream& input);
myClass() = default;
};
myClass myClass::create(const char* path)
{
std::ifstream input{ path, std::ios::binary | std::ios::in };
if (!input.is_open()) throw std::runtime_error("Error - couldn't open file");
return std::move(myClass(input));
}
myClass::myClass(myClass&& other) noexcept :
myStream(other.myStream)
{
other.myStream = std::cin;
}
myClass::myClass(std::istream& input) :
myStream(input)
{
}
int main()
{
const char* path = R"(file.bin)";
myClass cr{myClass::create(path)};
for (int i = 0; i < 10; i)
cr.myStream.seekg(i);
return 0;
}
CodePudding user response:
According to my tests, the error comes from the file path, you used a relative path when defining the path and the program cannot search for this file. After I changed the path to an absolute path, the program has no error.
You need to replace the path in const char* path = R"(C:\\Users\\Admin\\Desktop\\test.bin)";
with the path in your computer.
#include <fstream>
#include <iostream>
class myClass
{
public:
std::istream& myStream;
static myClass create(const char* path);
myClass(myClass&&) noexcept = default;
myClass(std::istream& input);
myClass() = default;
};
myClass myClass::create(const char* path)
{
std::ifstream input{ path, std::ios::binary | std::ios::in };
if (!input.is_open()) throw std::runtime_error("Error - couldn't open file");
return std::move(myClass(input));
}
myClass::myClass(std::istream& input) :
myStream(input)
{
}
int main()
{
const char* path = R"(C:\\Users\\Admin\\Desktop\\test.bin)";
myClass cr{ myClass::create(path) };
for (int i = 0; i < 10; i)
cr.myStream.seekg(i);
return 0;
}