Sign in to follow this  
__fold

Simple ifstream question

Recommended Posts

I have this very simple problem and it drives me insane. I think I've missed something in c++... I have this:
#ifndef SCRIPT_H
#define SCRIPT_H

#include <fstream>

class Script
{
private:
    std::ifstream in_;

protected:   
    std::string cachedMessage_;
    unsigned int currentLine_;
    
public:
    Script(void);   
    virtual ~Script(void);

    unsigned int getCurrentLine() { return currentLine_; }
    

    bool open(std::string inFile);
    std::string nextMessage();
};

#endif

and in c++
bool Script::open(std::string inFile)
{        
    in_.open(inFile.c_str()); //Crash!          
    return in_.is_open();
}

Now, the program crashes when in_.open() is called. It gives me an access violation. Why? If I make in_ local then it doesn't crash.

Share this post


Link to post
Share on other sites
You're not accidentaly doing something like this:

Script* s = 0;
.....
s->open("script.file");

Are you? It's happened to me before, quite annoying. Try breaking in Script::open and check that the this pointer is not null and is valid.

- Pete

Share this post


Link to post
Share on other sites
Pete_, yep, thanks, that's the problem...
I got tricked by the compiler since I had an other version of the open function that I could step through without any errors. But that one didn't access any members.

I almost did the same mistake just the other day but I found the problem right away then. Guess I'm tired...

thanks.

Share this post


Link to post
Share on other sites
Just as a note, __fold, you should be passing a const reference to that string, and not a string object. Passing the string object results in unnesessary copying.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this