|
-
August 7th, 2010, 05:47 PM
#16
Re: About vectors
 Originally Posted by ProgrammerC++
How does a vector know it goes out of scope?
How does any object you create knows it goes out of scope? There is nothing magical about vector -- all objects have a destructor that gets invoked automatically when the object goes out of scope.
Do you know what a destructor is and when it's called? If not, I suggest you read up on basic C++ fundamentals.
All objects that are declared have a scope, block scope, function scope, file scope, etc. When the object goes out of scope, the destructor is automatically invoked. The object doesn't "know" when it is or is not in scope, as it doesn't need to. Everything is taken care of by the language.
Code:
void f()
{
int a;
} // when this function is done, a is no longer in scope.
Do you understand this concept?
Regards.
Paul McKenzie
-
August 7th, 2010, 05:53 PM
#17
Re: About vectors
 Originally Posted by ProgrammerC++
Yes but where does it store the pointer to the object? It must be in newly allocated memory as soon as push_back is called
Nothing stops a vector implementation from using an array initially for fast access, and if the number of elements exceeds a certain size, switch to dynamically allocated memory. All of that is required of vector is that the memory used to store the items must be contiguous. Where that memory comes from doesn't matter.
All of this shouldn't be of concern to you. The vector knows how to handle its own memory very nicely without outside help. What you should be concerned with is using a vector properly, not how internally it does things.
Regards,
Paul McKenzie
-
August 8th, 2010, 09:07 AM
#18
Re: About vectors
Ah the compiler makes sure constructors and destructors are called for objects. I always thought constructors were only called on 'new' and 'delete'.
Well that makes things clear.
Thanks !
-
August 8th, 2010, 10:44 AM
#19
Re: About vectors
 Originally Posted by ProgrammerC++
Ah the compiler makes sure constructors and destructors are called for objects. I always thought constructors were only called on 'new' and 'delete'.
Well that makes things clear.
Thanks !
That's actually one of the reasons why you should prefer not to use "new"-----everything is more automatic if you don't. Sometimes new is necessary, but convince yourself it really is before you use it.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|