I'm wondering if RAII always allocates on the stack, or if the compiler ever uses the heap for large objects (and then perhaps adds a token to the stack as a sort of reminder of when to destroy the corresponding heap-allocated object)?
UPDATE: Apparently this question has been deemed unclear. Perhaps a code example will make this clearer:
In this code:
void dosomething() {
MyClass myclass();
}
Assuming the compiler didn't optimize away such a trivial example, does the instance of MyClass that's hereby created always get allocated on the stack, or is the heap ever used?
I think I understand the answer now thanks to the accepted answer -- the answer appears to be that the class instance itself goes on the stack while its contents may or may not depending on how its constructor was defined. Please add a comment/answer if this is incorrect.
The way you talk about RAII makes it sound like you have something of a mis-impression about the most fundamental idea of what RAII is. RAII (also known as SBRM--stack bound resource management, so no RAII isn't really entirely orthogonal to at least the concept of a stack) is basically a style of programming.
Programs written using RAII can and often do allocate memory from the free store. Such allocations, however, are handled by an object of some class. When the object is destroyed, the class' destructor executes, and that frees the dynamically allocated memory.
Just for example, a typical string
object will only contain a small amount of data, such as a pointer to the string's contents and an integer or two to keep track of the string size. When you create the string, it'll allocate some space from the free store to hold the actual data. When the string is destroyed, it'll automatically free that data. In some cases, it'll have some logic to avoid that free store allocation for small strings by allocating some small (fixed) amount of space in the string object itself, but doesn't change the basic idea.
So, the real answer is a qualified "yes". Yes, it's fairly common to have a small object that contains a pointer to some data allocated on the heap. Yes, the object will free that memory when the object itself is destroyed. But no, that's not something the compiler does for you. Rather, it's something you do in designing and implementing your classes.