Thread: C++ Arrays
View Single Post
Old 11-09-2006, 04:04 PM   #18 (permalink)
Sep102
Forum Expert
 
Join Date: Aug 2004
Location: Redmond, WA
Age: 21
Posts: 1,288
Send a message via AIM to Sep102 Send a message via MSN to Sep102
Default

Yes, it is wasting memory, for the duration of the constructor, then table is automatically cleaned up along with each of its entries while months sticks around with each of the entries on the heap, essentially trading "space" (constructing each month on the stack, which isn't very much of it in this case) and some time (default allocating months and copying table to months, still minuscule) for convenience.

I was trying to give an example that would use as much of milt's code as possible, had I wanted to give an optimized example, I would have, such as:
Code:
Month * table;
Calendar()
{
        // No need for default constructor and no extra work default
        // Constructing what we're about to reconstruct, yay!
	table = static_cast<Month *>(malloc(sizeof(Month) * 12));

	//initialize your private values, no temporaries here
        new(&table[0]) Month("January", 31);
	new(&table[1]) Month("February", 28);
	new(&table[2]) Month("March", 31);
	new(&table[3]) Month("April", 30);
	new(&table[4]) Month("May", 31);
	new(&table[5]) Month("June", 30);
	new(&table[6]) Month("July", 31);
	new(&table[7]) Month("August", 31);
	new(&table[8]) Month("September", 30);
	new(&table[9]) Month("October", 31);
	new(&table[10]) Month("November", 30);
	new(&table[11]) Month("December", 31);
}

~Calendar()
{
    for(Month *first = &table[0]; first != &table[12]; ++first)
    {
        first->~Month();
    }

    free(table);
}

I like the other example I gave more though, since it uses milt's code to construct the table on the stack and also looks quite a bit cleaner and easier to follow (especially from a more C# standpoint) than this or your example. Plus, you could just as easily have made table in some static const object that would contain all of the months for the life of the program that got copied to a member in Calendar each time a Calendar is constructed (if you want a mutable calendar, otherwise it could just hold a pointer to the table). All with minimal effort from what milt had above.

Last edited by Sep102; 11-09-2006 at 04:40 PM.
Sep102 is offline   Reply With Quote