Skip to content

Instantly share code, notes, and snippets.

@Gaurav-Singh-97
Created November 25, 2017 10:19
Show Gist options
  • Save Gaurav-Singh-97/9b52a65c3e50c673a2f06cbe47ebf41c to your computer and use it in GitHub Desktop.
Save Gaurav-Singh-97/9b52a65c3e50c673a2f06cbe47ebf41c to your computer and use it in GitHub Desktop.
Usage of shared_ptr in C++
#include<iostream>
#include<string>
#include<memory>
using namespace std;
class Book
{
string name;
public:
Book(string nm) : name(nm) { cout << "Book created with name \'" << nm << "\'\n"; }
~Book() { cout << "Book with name \'" << name << "\' destroyed\n"; }
string getName() { return name; }
};
int main()
{
// One way of assignment
shared_ptr<Book> sp1 (new Book("The C++ Programming Language"));
// Another way
shared_ptr<Book> sp2 = make_shared<Book>("Java for C++ Programmers");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment