如何将插入运算符与ifstream对象的shared_ptr指针一起使用
How to use insertion operator with a shared_ptr pointer of an ifstream object?
我正在尝试使用shared_ptr指针读取文件。我不知道如何使用插入运算符。下面是代码:
#include <iostream>
#include <regex>
#include <fstream>
#include <thread>
#include <memory>
#include <string>
#include <map>
using namespace std;
int main()
{
string path="";
map<string, int> container;
cout<<"Please Enter Your Files Path: ";
getline(cin,path);
shared_ptr<ifstream> file = make_shared<ifstream>();
file->open(path,ifstream::in);
string s="";
while (file->good())
{
file>>s;
container[s]++;
s.clear();
}
cout <<"nDone..."<< endl;
return 0;
}
简单操作:
file>>s;
不起作用。
如何获取文件所指向的当前值(我不想获取整行,我只需要通过这种方式获取单词及其出现次数)。
顺便说一句,我使用shared_ptr来避免自己关闭文件,制作这种类型的指针shared_ptr(智能),不自己编写file->close()
就足够了吗?或者它们无关紧要?
最简单的方法是使用解引用operator *
:
(*file) >> s;
但从代码来看,我看不出有任何理由使用智能指针。您可以只使用一个ifstream
对象。
std::ifstream file(path); // opens file in input mode
为什么希望它是指针?正是它给你带来了痛苦。
ifstream file;
file.open( ...
...
file>>s;
流被视为值(而不是指针类型)。当在ifstream
上调用析构函数时,该文件将被关闭。
如果您需要在代码的其他部分传递流对象,只需使用引用(对基类):
void other_fn( istream & f )
{
string something;
f>>something;
}
ifstream file;
other_fn( file );
因为f
参数是一个引用,所以当流/文件超出作用域时,它不会尝试关闭它——这种情况仍然发生在定义原始ifstream
对象的作用域中。
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 无法使用 libtool 将 -shared 参数传递给 g++
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- shared-ptr-C++shared_ptr与unique_ptr用于资源管理