What are the primary differences between stack and heap memory allocation in C++, and when would you optimize for one over the other?