Before I answer your question directly, allow me to interrupt:
1 2 3
|
vector<object*> objpoints;
[snip]
objpoints.push_back(new object());
|
I do not recommend this, because now you can't remove elements from that vector without deleting them first. Which also means you have to have a dtor in whatever class own that vector, and you have to manually delete each item.
General rule of thumb: if you are manually deleting, you are doing something wrong.
Another general rule of thumb: if you are using new, whatever you're new'ing should be going
directly into a smart pointer.
A better approach:
1 2 3
|
vector<unique_ptr<object>> objpoints;
objpoints.emplace_back( new object() );
|
Since you have a vector of smart pointers, they will be automatically deleted when the vector is destroyed, or when individual elements are removed. With this, there is practically 0 risk of memory leaks.
As for your actual question...
to add to objlist I can objpoints.push_back(object());
In the [above] case, I'm guessing the the temporary object falls out of scope as soon as the push_back is called, and ends up corrupting memory by trying to copy from that position with object's copy constructor? |
No. The above call will work exactly how you expect.
1) Temporary object is constructed
2) Copy ctor called to put that temporary object into the vector
3) Temporary destroyed
or... with optimizations enabled ... what is more likely is that the compiler will optimize the temporary/copy away, and simply put the object into the vector directly.
Either way the code will do what you want and work correctly. The only way it wouldn't is if your object class does not copy itself correctly or if you rely on the 'this' pointer somehow.
If I want to allocate something on the stack, |
If it's in a vector, it's on the heap. If it's dynamically allocated, it's on the heap.
"On the stack" basically equates to "declared locally in a function":
1 2 3 4 5 6 7
|
void func()
{
int foo = 5; // foo is on the stack
vector<int> woo; // woo is on the stack
woo.push_back(foo); // inside the vector, a copy of foo is made on the HEAP
}
|
Note this might not always be 100% true as it depends on the implementation of vector.... but generally speaking.
Though whether or not something is on the stack typically doesn't matter.