*SNIP - After clarification of the scenario, I posted this answer in a comment originally *
How about this. In your stack, store unique_ptrs. When you pop from the stack, you grab the raw pointer from the unique_ptr and shove it into another unique_ptr - this second one is declared with a custom deleter which, on destruction, retains the location of the stack and performs the reverse of the pop operation. This will work with shared_ptr too but obviously it depends on what you need.
It's independent of the type of B, and could be encapsulated entirely in the stack class (barring the unique_ptr+deleter type, but that would just be a typedef).