除了C ++,其他语言的程序员是否使用,知道或理解RAII? [英] Do programmers of other languages, besides C++, use, know or understand RAII?

查看:190
本文介绍了除了C ++,其他语言的程序员是否使用,知道或理解RAII?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述














$ b

所以我真的很好奇,如果这是因为我每天被硬核C ++程序员包围,RAII只是不是一般知名的(包括C + +),或者如果所有这些问题在Stackoverflow是由于我现在接触的程序员不是与C ++成长,在其他语言的人只是不使用/知道RAII?



<$ p $

对于在这个线程中评论RAII(资源获取是初始化)的人来说,这是一个激励的例子。 p> class StdioFile {
FILE * file_;
std :: string mode_;

static FILE * fcheck(FILE * stream){
if(!stream)
throw std :: runtime_error(Can not open file);
return stream;
}

FILE * fdup()const {
int dupfd(dup(fileno(file_)));
if(dupfd == -1)
throw std :: runtime_error(Can not dup file descriptor);
return fdopen(dupfd,mode_.c_str());
}

public:
StdioFile(char const * name,char const * mode)
:file_(fcheck(fopen(name,mode))),mode_ (模式)
{
}

StdioFile(StdioFile const& rhs)
:file_(fcheck(rhs.fdup())),mode_(rhs.mode_ )
{
}

〜StdioFile()
{
fclose(file_);
}

StdioFile& operator =(StdioFile const& rhs){
FILE * dupstr = fcheck(rhs.fdup());
if(fclose(file_)== EOF){
fclose(dupstr); // XXX ignore failed close
throw std :: runtime_error(Can not close stream);
}
file_ = dupstr;
return * this;
}

int
read(std :: vector< char>& buffer)
{
int result(& buffer [0 ],1,buffer.size(),file_));
if(ferror(file_))
throw std :: runtime_error(strerror(errno));
return result;
}

int
write(std :: vector< char> const& buffer)
{
int result ],1,buffer.size(),file_));
if(ferror(file_))
throw std :: runtime_error(strerror(errno));
return result;
}
};

int
main(int argc,char ** argv)
{
StdioFile file(argv [1],r);
std :: vector< char>缓冲器(1024);
while(int hasRead = file.read(buffer)){
//进程hasRead字节,然后将它们从缓冲区中移出
}
}

这里,当创建 StdioFile 实例时,资源,在这种情况下);当它被销毁时,资源被释放。没有 try finally 如果读取导致异常, fclose 会自动调用,因为它在析构函数中。



析构函数当函数离开 main 时调用,无论是正常还是异常。在这种情况下,文件流被清理。世界再次安全。 :-D


I've noticed RAII has been getting lots of attention on Stackoverflow, but in my circles (mostly C++) RAII is so obvious its like asking what's a class or a destructor.

So I'm really curious if that's because I'm surrounded daily, by hard-core C++ programmers, and RAII just isn't that well known in general (including C++), or if all this questioning on Stackoverflow is due to the fact that I'm now in contact with programmers that didn't grow up with C++, and in other languages people just don't use/know about RAII?

解决方案

For people who are commenting in this thread about RAII (resource acquisition is initialisation), here's a motivational example.

class StdioFile {
    FILE* file_;
    std::string mode_;

    static FILE* fcheck(FILE* stream) {
        if (!stream)
            throw std::runtime_error("Cannot open file");
        return stream;
    }

    FILE* fdup() const {
        int dupfd(dup(fileno(file_)));
        if (dupfd == -1)
            throw std::runtime_error("Cannot dup file descriptor");
        return fdopen(dupfd, mode_.c_str());
    }

public:
    StdioFile(char const* name, char const* mode)
        : file_(fcheck(fopen(name, mode))), mode_(mode)
    {
    }

    StdioFile(StdioFile const& rhs)
        : file_(fcheck(rhs.fdup())), mode_(rhs.mode_)
    {
    }

    ~StdioFile()
    {
        fclose(file_);
    }

    StdioFile& operator=(StdioFile const& rhs) {
        FILE* dupstr = fcheck(rhs.fdup());
        if (fclose(file_) == EOF) {
            fclose(dupstr); // XXX ignore failed close
            throw std::runtime_error("Cannot close stream");
        }
        file_ = dupstr;
        return *this;
    }

    int
    read(std::vector<char>& buffer)
    {
        int result(fread(&buffer[0], 1, buffer.size(), file_));
        if (ferror(file_))
            throw std::runtime_error(strerror(errno));
        return result;
    }

    int
    write(std::vector<char> const& buffer)
    {
        int result(fwrite(&buffer[0], 1, buffer.size(), file_));
        if (ferror(file_))
            throw std::runtime_error(strerror(errno));
        return result;
    }
};

int
main(int argc, char** argv)
{
    StdioFile file(argv[1], "r");
    std::vector<char> buffer(1024);
    while (int hasRead = file.read(buffer)) {
        // process hasRead bytes, then shift them off the buffer
    }
}

Here, when a StdioFile instance is created, the resource (a file stream, in this case) is acquired; when it's destroyed, the resource is released. There is no try or finally block required; if the reading causes an exception, fclose is called automatically, because it's in the destructor.

The destructor is guaranteed to be called when the function leaves main, whether normally or by exception. In this case, the file stream is cleaned up. The world is safe once again. :-D

这篇关于除了C ++,其他语言的程序员是否使用,知道或理解RAII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆