operator=不适用于fstream

operator = does not work with fstream

本文关键字:fstream 适用于 不适用 operator      更新时间:2023-10-16

我有一个结构

struct myStruct {
    fstream fp;
    char *buffer;
    size_t size;
};

我是C++的新手,正在尝试编写一个代码,其中一个线程将从一个文件读取到缓冲区,主线程将缓冲区写入另一个文件。代码示例如下:

int main() {
    pthread tid1;
    struct myStruct readArgs;
    fstream fileP, fileP2;
    fileP.open("/tmp/20MBFile", fstream::in);
    fileP2.open("/tmp/trial-file", fstream::out);
    char *buffer;
    readArgs.fp = fileP;
    readArgs.buffer = buffer;
    readArgs.size = 1048576;
    pthread_create(&tid1, NULL, Read, &readArgs);
    pthread_join(tid1, NULL);
    fileP2.write(buffer, 1048576);
    ......
}

读取功能如下:

void *Read(struct myStruct *readArgs) {
    readArgs->fp.read(readArgs->buffer, readArgs->size);
    pthread_exit(NULL);
}

然而,当我编译代码时,我会出现以下错误:

错误:使用已删除的函数"std::basic_stream&std::basic_stream::operator=(const std::basic_stream&)'readArgs.fp=文件P;

错误:从"void*()(myStruct)"到"void*pthread_create(&tid1,NULL,Read,&readArgs);^在/usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../../include/c++/4.8.3/x86_64-redhat-linux/bits/gthr default.h:35:0中包含的文件中,从/usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../include/c++/4.8.3/x86_64-redhat-linux/bits/gthr.h:148,从/usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../include/c++/4.8.3/ext/atomicity.h:35,从/usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../include/c++/4.8.3/bits/ios_base.h:39,从/usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../include/c++/4.8.3/ios:42,从/usr/lib/gcc/x86_64-redhat-linux/4.8.3/../../include/c++/4.8.3/ostream:38,来自/usr/lib/gcc/x86_64-redhat-
……
/usr/include/phread.h:232:12:错误:初始化"int pthread_create(pthread_t*,const pthread_attr_t*,void*()(void),void*)"的参数3[-fpermission]extern int pthread_create(pthread_t*__restrict__newthread,

我是不是遗漏了什么?提前感谢!

找到了答案
1.不能使用=分配fstream-fstream,但可以移动。由于gcc版本的原因,swap()也不起作用。我有gcc版本4.8.3.x,我想它不支持fstreamswap()调用
2.pthread_create()-它需要签名为void *foo(void *)的函数,因此必须传递所需的参数,并在所需函数中进行类型转换
在这里我会这样做:

pthread_create(&tid1, NULL, Read, &readArgs);

Read()的功能是:

void *Read(void *args) {
    myStruct *readA = (myStruct *)args;  
    ....
}  

感谢大家抽出时间!