你知道stdin由文件名" - "指定的常见stdio习语,例如
if ((strcmp(fname, "-"))
fp = fopen(fname);
else
fp = stdin;
Run Code Online (Sandbox Code Playgroud)
使用ifstream实例执行此操作的最佳方法是什么?我收到了一些代码,它有ifstream一个类的一部分,我想添加代码来做同等的事情,比如:
if ( filename == "-")
logstream = cin; // **how do I do this*?*
else
logstream.open( filename.c_str() );
Run Code Online (Sandbox Code Playgroud) 我想知道静态对象上的智能指针是否合理.例如,假设我有一些静态资源,并希望将对该静态资源的引用传递给需要使用这些资源的其他对象.
一种方法是使用指向该资源的RAW指针.但现在我想知道智能指针(shared_ptr)是否是更好的方法,如果是这样,如何正确地做到这一点.(智能指针也应该是静态的吗?).
问题的背景:如果没有更多的对象持有智能指针,智能指针指向的静态对象将被释放(这不是最好的想法......).
一个例子(在运行结束时以崩溃结束):
struct SomeType {
SomeType() { cout << "ctor..." << endl; }
~SomeType() { cout << "dtor..." << endl; }
void sayHello() { cout << "Hello!" << endl; }
};
void someFunction(shared_ptr<SomeType> smartPointer) {
smartPointer->sayHello();
}
static SomeType st;
static shared_ptr<SomeType> pt{ &st };
void anotherFunction() {
someFunction(pt);
}
int main() {
anotherFunction();
cin.get();
}
Run Code Online (Sandbox Code Playgroud)