Access violation with ifstream

Access violation with ifstream

Post by Sebastian Faus » Sat, 30 Nov 2002 09:21:16



Hi,
I have written the following code:

#include <fstream>

class A
{
public:
 A() {};
 A(const std::ifstream& str) : str_(str)
 {
 };
private:
 std::ifstream str_;

Quote:};

int main(int argc, char* argv[])
{
 std::ifstream is;

 is.open("C:\\t1.txt", std::ios::binary);
 A a(is);
 is.close();

 return 0;

Quote:}

When I leaf the main function then I got an access violation. Why does that
happen? How can I copy an ifstram-object?

Thanks in advance

 
 
 

Access violation with ifstream

Post by Gerhard Prilmeie » Sat, 30 Nov 2002 10:17:04




Quote:> Hi,
> I have written the following code:

> #include <fstream>

> class A
> {
> public:
>  A() {};
>  A(const std::ifstream& str) : str_(str)
>  {
>  };
> private:
>  std::ifstream str_;
> };

> int main(int argc, char* argv[])
> {
>  std::ifstream is;

>  is.open("C:\\t1.txt", std::ios::binary);
>  A a(is);
>  is.close();

>  return 0;
> }

> When I leaf the main function then I got an access violation. Why does
that
> happen? How can I copy an ifstram-object?

You can not copy it. I consider it an error of your implementation not to
tell you so. (a ifstream disables its copy constructor) Not sure what the
standard requires here though.

Depending on your needs, you may have to work with pointers or references to
the ifstream.
Using references, your class would possibly read as follows:

class A
{
public:
A(const std::ifstream& str) : str_(str)
{

Quote:};

private:
const std::ifstream& str_;

Quote:};

Note that the default constructor has to be removed, as you have to somehow
initialize the reference.

hth,
Gerhard

 
 
 

Access violation with ifstream

Post by Sebastian Faus » Sat, 30 Nov 2002 10:40:21


Hi,

thanks for your answer.

Quote:

> You can not copy it. I consider it an error of your implementation not to
> tell you so. (a ifstream disables its copy constructor) Not sure what the
> standard requires here though.

> Depending on your needs, you may have to work with pointers or references
to
> the ifstream.
> Using references, your class would possibly read as follows:

> class A
> {
> public:
> A(const std::ifstream& str) : str_(str)
> {
> };
> private:
> const std::ifstream& str_;
> };

> Note that the default constructor has to be removed, as you have to
somehow
> initialize the reference.

Remove the default constructor means to make it private or not?

Thanks in advance
Sebastian

 
 
 

Access violation with ifstream

Post by Karl Heinz Buchegge » Sat, 30 Nov 2002 18:24:31



> Remove the default constructor means to make it private or not?

In this case: No.
Since you have another constructor, the compiler will not generate
a default constructor on it's own.

--
Karl Heinz Buchegger