@JonB said in Stack/Heap/smart pointers question.:
the size of an object which is to be allocated on the stack must be known at compile time, there is no workaround for this, it's an architectural "issue".
Now, you know I always read what you write with interest, my friend! But I don't understand why you pick this out as a "stricture" of stack allocation?
For the purpose of pedagogy. There's a gnu extension which allows you a stack based array with a runtime constant as size, as well, but it's not standard.
What about alloca(), which has been there since year dot in Unix, and I see is still supported by gcc and in msvc (_alloca())?
Did not mention it, and specifically avoided it, because the memory isn't freed when you leave the current scope, it's freed when the stack frame's popped. This is rather dangerous and can be messy. And in the C++ world *alloc() functions are discouraged in most cases. If you want an array of objects and you take the memory block through alloca you need to do a placement new on top of it to follow C++ semantics, so your constructors are called, and finally you need to manually invoke the destructors before exiting. This isn't ideal in the world of RAII.
I'm not suggesting people go out and start using it, but it does not require a compile-time constant argument, so how does this relate to your "architectural" claim above?
Not too well. I was specifically thinking of push and pop. Granted, alloca will move the top of the stack frame, and as with any integer that can be done at runtime, but it's a bad idea generally. In fact this is what the compiler does when you do a regular stack allocation - it moves the stack pointer the size of the object off the stack frame pointer (i.e. move the esp register in relation to the ebp register), with the exception that it validates the consistency at compile time (and static code analysis can be easily supported). Also the meaning is clearer, as you know the memory is local. With alloca you can pass the pointer to somewhere else, and without realizing that pointer's data block can get invalidated the moment you leave the current stack frame. It's not for the faint of heart.