2

I don't think I have mastered shared_ptr.

Example code:

shared_ptr<ofstream> logger;
int main(){

    logger = make_shared<ofstream>(new ofstream("ttt.txt"));
    *logger <<"s";
    return 0;
}

Error 1 error C2664: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream(const char *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::basic_ofstream<_Elem,_Traits> ' to 'const char *' c:\program files (x86)\microsoft visual studio 10.0\vc\include\xxshared 13

Edited:

[
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.  
] 

I don't know how to make this happen. Or maybe it's nonsense at all. Hope any one can throw an idea or point out the lacking part of my understanding on shared_ptr.

Chris Su
  • 543
  • 8
  • 16

1 Answers1

6

The make_shared function takes arguments that will be passed to the constructor of T; the point of make_shared is to avoid the extra allocation made by constructing your shared_ptr with new.

In your case, you want to construct an ofstream using it's ofstream(const char*) constructor, so you should just use make_shared<ofstream>("ttt.txt").

Regarding your edit, if your application crashes, you shouldn't be trying to clean up resources. Something terrible happened to make it crash, and who knows what state it's in; you could actually cause damage by attempting to do anything. With that said, your operating system will clean up most resources owned by the application, such as file handles, when the application is terminated, either gracefully or ungracefully.

Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71
  • Thanks for your answer. But what's the difference between make_shared and shared_ptr(new T()); – Chris Su Oct 25 '13 at 21:27
  • 1
    @ChrisSu: The difference is that you don't have to use `new` yourself. This has two benefits: (1) there's no danger of an exception causing a memory leak before initialising the shared pointer; (2) `make_shared` is more efficient since it can allocate memory for both the object and the shared control structure in a single allocation, where you'd need two if you allocated the object yourself. – Mike Seymour Oct 25 '13 at 21:41
  • @MikeSeymour Thanks a lot. This is helpful and convicing. – Chris Su Oct 25 '13 at 23:23