I've been messing around with pointers, objects and vectors so I can get some practice and I'm making a little program that simulates the stock market. In it I have a "Share" class which simulates the behavior of a real share or share index.
I had a static function that push_back()ed new Share's into a static Share* vector, which was something like this:
void loadShares()
{
shares.clear();
shares.push_back(new Share(...));
shares.push_back(new Share(...));
shares.push_back(new Share(...));
shares.push_back(new Share(...));
This worked fine for the first 'push_back()' but caused a memory access violation for the second or third similar statment. After a few days of researching what could have caused the error and the nature of the 'new' operator, I eventually tried making a static Share* function, called 'newShare(...)', which was something like this:
Share* Share::newShare(...)
{
Share* returnShare = NULL;
returnShare = new Share(...); //'passing on' the arguments into the constructor
return returnShare;
I then used it like this:
...//in the loadShare() method shares.push_back(newShare(...));
This function worked perfectly, and this must be because I'm initializing the poiner to NULL. What my question is though, is if a pointer is not NULL, and it holds some rubbish value and 'new' is called onto it, does the allocation of memory happen to the address it holds, while if it were NULL an unused block of memory is found first?
NOTE: sorry about the title, I know not to use things like "PLZ HELP" etc, but i literally saw the "question about" as I pressed enter and I couldn't stop my laggy internet connection from doing what I'd asked.

New Topic/Question
Reply



MultiQuote





|