loop
loop

Reputation: 3590

C++ lifespan of temporary object passed to constructor

I have a class that accepts an istream reference in the constructor. If the constructor is passed a temporary object like myclass obj(ifstream("filename")); will that ifstream be good for the life of obj? Does it depend on whether or not it is assigned to a reference or pointer in the class?

For example:

class test
{
public:
    istream *p;
    test(istream &is)
    {
        p = &is;
        cout << "a constructor" << endl;
    }
    ~test()
    {
        cout << "a destructor" << endl;
    }
    bool isgood()
    {
        return p->good();
    }
};

int main()
{
    test test(ifstream("test.cpp"));
    cout << test.isgood() << endl;
}

Output:

a constructor
1
a destructor

Just because the output says the file is good I don't know if it's been destroyed or what. If there is a part of the standard that covers this please let me know. Thanks

Upvotes: 0

Views: 322

Answers (1)

james
james

Reputation: 262

Sorry, I don't have enough reputation to comment.

The temporary istream is good only in the constructor. Even though you use the address of the istream to set the value of the pointer, you can no longer use it once the constructor has returned. Since after the constructor call, the temporary ifstream has already been closed and destructed. So the pointer will be pointing to garbage as @Josh mentioned. You may modify your code to pass the filename into the constructor and use the filename to initialize an member ifstream (not a pointer to ifstream). Then you can use the stream through the lifespan of the object.

Upvotes: 2

Related Questions