fstream指针没有指向

时间:2012-01-22 05:14:53

标签: c++ pointers fstream

我正在尝试创建一个指向fstream的指针,因此我可以在所有类方法中使用它:

class P
{
    private:
        fstream *fs;

    public:
        P()
        {
            fstream fs(filepath, openmode);
            this->fs = &fs;
        }
};

但它似乎并没有指向它,例如我写道:

fs->is_open() 

它将返回false,而如果我写:

fs.is_open()

它将返回true。

造成这种情况的原因是什么?我也尝试将指针更改为fstr之类的指针,但这也没有用。

3 个答案:

答案 0 :(得分:4)

您将成员指针fs指向本地创建的fstream对象,一旦其本地作用域结束就不存在,您剩下的是一个悬空指针。

您的this->fs现在指向不存在的内容。

每当您使用此悬空指针对流进行操作时,都会导致未定义行为

答案 1 :(得分:4)

要完成您的要求,您需要使用new运算符,如下所示:

SmartIO::SmartIO(const char * filepath , Mode mode)
    : fs(NULL), buffer(NULL), offset(0)
{
    switch (mode)
    {
        case Mode::inText:
        {
            fs = new fstream(filepath,fstream::in|fstream::ate);
            break;
        }
        case Mode::inBinary:
        {
            fs = new fstream(filepath,fstream::in|fstream::binary|fstream::ate);
            break;
        }
    }

    if ((fs) && (fs->is_open()))
    {
        buffer = new std:vector<char>(fs->tellg(), 0);
        fs->seekg(0, ios::beg);
        fs->read(buffer->data(), buffer->size());
    }
    else
    {
        printf( "cant open the file!");
    }
}

SmartIO::~SmartIO()
{
    delete fs;
    delete buffer;
}

答案 2 :(得分:2)

您需要动态创建实际的流对象。这样的事情可能是一种方法:

class Foo
{
    std::istream * p;
    bool must_clean;
public:
    Foo() : p(nullptr), must_clean(false)
    {
        if (...)      { p = new std::ifstream("somefile.txt"); must_clean = true; }
        else if (...) { p = new std::istringstream(global_buf); must_clean = true; }
        else          { p = &std::cin; }
    }
    ~Foo() { if (must_clean) delete p; }
    Foo(Foo const&) = delete;
    Foo & operator=(Foo const&) = delete);
};

您可以决定是否需要istreamostreamiostream指针。

相关问题