fork download
#include 
#include 
#include 

struct Song
{
    Song( const std::string& name, const std::string& by )
        : title(name), artiste(by) { std::cout << "Song::two arg constructor\n" ; }

    Song( const Song& that ) : title(that.title), artiste(that.artiste)
    { std::cout << "Song::copy constructor\n" ; }

    const std::string title ;
    const std::string artiste ;
};

int main()
{
    std::vector favourites ; // empty sequence
    favourites.reserve(5) ; // reserve space for upto 5 songs

    Song autumn( "Autumn in New York", "Billie Holiday" ) ; // Song::two arg constructor
    favourites.push_back(autumn) ; // vector makes a copy: Song::copy constructor


    std::cout << '\n' ;
    // 1. construct an anonymous song object and pass that to push_back()
    // 2. the vector makes a copy
    favourites.push_back( Song( "Summertime", "Sarah Vaughan" ) ) ;
    // Song::two arg constructor
    // Song::copy constructor


    std::cout << '\n' ;
    // construct a song object in situ inside the vector (avoids the extra copy)
    favourites.emplace_back( "It Might as Well Be Spring", "Astrud Gilberto" ) ;
    // Song::two arg constructor


    std::cout << '\n' ;
    // allocate memory for a new buffer which can hold upto 50 songs
    // copy the three songs into the new buffer
    favourites.reserve(50) ; // reserve space for upto 5 songs
    // Song::copy constructor
    // Song::copy constructor
    // Song::copy constructor
}
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
Song::two arg constructor
Song::copy constructor

Song::two arg constructor
Song::copy constructor

Song::two arg constructor

Song::copy constructor
Song::copy constructor
Song::copy constructor