简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM