> Am I right to think that both a and literal value 10 are stored in the stack
> And also, is correct to say that b is stored in the stack while 20 is stored in the heap?
No and no.
The language specification for C++ (as specified in the IS) is only concerned about the lifetime of an object (and the duration for which the storage for an object would be available). The IS uses an abstract concept called 'storage duration' for this.
In the example above,
a has
automatic storage duration. The life-time of the object begins when the function
myFunction is called and ends when the function returns (the enclosing block is exited from). The standard does not have anything to say from where or how an implementation should allocate storage for the object.
On the other hand, the int represented by the literal
10 is a
prvalue (pure rvalue); since a situation that requires the
temporary materialization of this
prvalue does not exist, it is typically not associated with any object.
http://en.cppreference.com/w/cpp/language/implicit_conversion#Temporary_materialization
Since when we talk about 'stack', 'heap' etc., we are referring to specific implementation details, to complete the picture, we would also have to consider the "as-if" rule.
http://en.cppreference.com/w/cpp/language/as_if
For instance, a compiler could (should) rewrite the program as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
// this function has external linkage; it can't be removed (unless link-time optimisation is enabled)
void myFunction (int * a) {
*a = 10;
}
int main () {
void* pv = ::operator new( sizeof(int) ) ; // the int initialised with the value 20 is optimised away
std::cout << 10 << "\n" ; // print 10
::operator delete(pv) ;
}
|