//Hi all,could someone explain the make_shared(), is it used to substitute constructor?
//Here is an example
void DoAddStaff(vector<Ptr>& container)
{
    cout << "\nEnter type of employee to add ('W' for waged, 'S' for salaried): ";
    char c;
    cin >> c;
    cin.ignore();

    if( c == 'w' || c == 'W' )
    {
        cout << "\nEnter waged employee's name: ";
        string name;
        getline(cin, name);

        cout << "\nEnter waged employee's hourly rate of pay: ";
        double rate;
        cin >> rate;
        cin.ignore();


        container.push_back( make_shared<CWagedEmployee>(name, CreateEmplNum( container ), rate) );
    }

    else if( c == 's' || c == 'S' )
    {
        cout << "\nEnter salaried employee name: ";
        string name;
        getline(cin, name);

        cout << "\nEnter employee's salary: ";
        double salary;
        cin >> salary;



        container.push_back( make_shared<CSalariedEmployee>(name, CreateEmplNum( container ), salary) );
    }
    else
        cout << "Wrong type." << endl;

Edited 2 Years Ago by aluhnev

is it used to substitute constructor?

Yes. An exception-safe and (usually) more efficient substitute.

This function is typically used to replace the construction std::shared_ptr<T>(new T(args...)) of a shared pointer from the raw pointer returned by a call to new.

In contrast to that expression, std::make_shared<T> typically allocates memory for the T object and for the std::shared_ptr's control block with a single memory allocation (this is a non-binding requirement in the Standard), where std::shared_ptr<T>(new T(args...)) performs at least two memory allocations.

Moreover, code such as f(std::shared_ptr<int>(new int(42)), g()) can cause a memory leak if g throws an exception because g() may be called after new int(42) and before the constructor of shared_ptr<int>. This doesn't occur in f(std::make_shared<int>(42), g()), since two function calls are never interleaved.
- http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared

This article has been dead for over six months. Start a new discussion instead.