相关疑难解决方法(0)

C++:将cin分配给ifstream变量?

你知道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)

c++ iostream ifstream

16
推荐指数
1
解决办法
1万
查看次数

shared_ptr对静态对象有好处吗?

我想知道静态对象上的智能指针是否合理.例如,假设我有一些静态资源,并希望将对该静态资源的引用传递给需要使用这些资源的其他对象.

一种方法是使用指向该资源的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)

c++ static pointers smart-pointers c++11

2
推荐指数
2
解决办法
5831
查看次数

标签 统计

c++ ×2

c++11 ×1

ifstream ×1

iostream ×1

pointers ×1

smart-pointers ×1

static ×1