Spoiler just contains background and context
! This post mentions that, to get around the fact that when object goes out of scope it is deallocated, simply return the object the stack-allocated object so it remains in scope. This apparently makes a copy of the object on the stack somewhere else. This guy even confirms that you should always prefer allocating to stack. In C++, using something like:
!
Object* my_object = new Object();
! Dynamically instantiates an object to the heap, yet !
Object my_object = Object();
! Instantiates an object on the stack. The stack is limited in size whereas the heap is practically not (other than physical limits). But also, according this this post, stack access time is much faster, and of course the deallocation is automatic when it goes out of scope.
I'm trying to create an application where speed is absolutely critical, can't I just instantiate all of my objects on the stack within main, and simply save every instantiation that's within a nested scope to an outside container?
I tested this myself using a simple Node class that contains the property "id". I instantiated the nodes on the stack, put them in a vector so they don't get deallocated, then (just to check) I allocated new items to the stack and then checked to make sure the data to the previous allocations still existed. Can I continue to implement this on a somewhat large-scale problem?
int main()
{
vector<Node> stack_nodes;
for (int i = 0; i < 2; ++i)
{
stack_nodes.push_back(Node(i)); // push newly copied stack-allocated objects so they don't die
}
Node new_node1 = Node(3); // allocate two more to test stack memory overwriting
Node new_node2 = Node(4);
cout << stack_nodes.at(1).getID(); // outputs 1! It's still there?
return 0;
}
EDIT: See comments below. When you return the stack-allocated object from the scope it was created in, a copy of said object is created. Is that copy also on the stack? If I assign that copied object to a vector declared in the scope of main, will that object still be on the stack?