shared_ptr <T>如何访问T的元素或函数

Chr*_* Su 2 c++ shared-ptr c++11

我不认为自己掌握了shared_ptr.

示例代码:

shared_ptr<ofstream> logger;
int main(){

    logger = make_shared<ofstream>(new ofstream("ttt.txt"));
    *logger <<"s";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误1错误C2664:'std :: basic_ofstream <_Elem,_Traits> :: basic_ofstream(const char*,std :: ios_base :: openmode,int)':无法从'std :: basic_ofstream <_Elem,_Traits>转换参数1 'to'conc char*'c:\ program files(x86)\ microsoft visual studio 10.0\vc\include\xxshared 13

编辑:

[
In the mean time, if I wanna close the ofstream while some crashes happened. 
How can I do it? 
I mean if shared_ptr release the memory without closing the file. 
There would be problems.  
] 
Run Code Online (Sandbox Code Playgroud)

我不知道如何实现这一目标.或许这根本就是胡说八道.希望任何人都可以提出一个想法或指出我理解中缺乏的一部分shared_ptr.

Col*_*nee 6

make_shared函数接受将传递给构造函数的参数T; 点make_shared是避免通过构建您做出额外的分配shared_ptrnew.

在你的情况下,你想构造一个ofstream使用它的ofstream(const char*)构造函数,所以你应该使用make_shared<ofstream>("ttt.txt").

关于编辑,如果您的应用程序崩溃,您不应该尝试清理资源.可怕的事情让它崩溃,谁知道它处于什么状态; 你可以通过尝试做任何事情来造成伤害.话虽如此,当应用程序终止时,您的操作系统将清理应用程序拥有的大多数资源,例如文件句柄,无论是优雅还是不正常.