Disclaimer: ‘stack’ is not part of the c++ standard to my knowledge, there we have ASDVs (automatic storage duration variables). ABI might define stack. Note that sometimes these are passed in registers, which I believe is OK in your case.
Define a CPS (continuation-passing style) factory method:
class A {
public:
template<typename F, typename... Args>
static auto cps_make(F f, Args&&... args) {
return f(A(std::forward<Args>(args)...));
}
private:
A(/* ... */) {}
A(const A&) = delete;
A(A&&) = delete;
};
Usage: pass a lambda taking A and the ctor parameters of A. E.g.
return A::cps_make([&](A a) {
/* do something with a */
return true;
});
Function arguments are always ASDVs inside.
How the code works: cps_make takes a functor (usually a lambda) which takes an instance of the given type; and optional ctor parameters. It creates the instance (by forwarding any optional params to the ctor), calls the functor and returns what the functor returns. Since the functor can be a lambda in C++11, it doesn’t break the normal code flow.
The beauty of CPS is, you can have static polymorphism just by using an auto-lambda in C++14: your cps_make() can create just about anything you wish (hierarchy, variant, any, etc.). Then you save the virtual overhead for closed hierarchies. You can even have a lambda for normal flow and one if ctor would fail; this comes handy when exceptions are no-go.
The drawback is, currently you can’t directly use the control flow statements of the outside scope inside the lambda. /* Hint: we’re working on it. */