Why do the various insertion members (insert, push_back, etc...) in the STL 
containers take a parameter as input if they will eventually be placed on the 
heap? Isn't this a limitation since you first usually have to create an 
automatic variable, initialize it, and copy it to the heap? Wouldn't it have 
been more efficient to just allow the caller to initialize it directly on the 
heap (as done typically in C data structures)?

I hope this is clear, but I have included some code to convey what I'm thinking.

-----------------------------------------------------

#include <vector>
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;

class BigObject {
  private:
        char data[ 4096 ];

  public:
        BigObject( )
        {
                // Intentional don't initialize members.
                cout << "Uninitialized Constructor." << endl;
        }

        BigObject( unsigned int n )
        {
                initialize( n );
                cout << "Constructed." << endl;
        }

        BigObject( BigObject const& o )
        {
                memcpy( data, o.data, 4096 );
                cout << "Copied" << endl;
        }

        void initialize( unsigned int n )
        {
                if( n > 256 ) n = 256;

                for( size_t i = 0; i < 4096; i++ )
                {
                        data[ i ] = rand( ) % n;
                }
                cout << "Initialized." << endl;
        }
};

int main( int argc, char *argv[] )
{
        vector<BigObject> collection;

        // This creates one big object on the stack.
        BigObject myObject( 157 ); 

        // This will copy this big object onto the heap.
        collection.push_back( myObject ); 

        // Is there any way to avoid placing the big object on the stack
        // in the first place? (i.e. initialize directly on the heap)
        // Is this really a performance concern?
        
        return 0;
}





      

Reply via email to