I asked myself if it was possible to write a class which objects could only be created on the stack. This resulted in
this question.I'll repeat the code in question:
#include <cstddef>
#include <iostream>
class Foo {
public:
static Foo createOnStack() { return {}; }
~Foo () { std::cout << "Destructed " << --i << std::endl; }
private:
static int i;
Foo () { std::cout << "Created " << i++ << std::endl; }
Foo (const Foo &) = delete;
};
int Foo::i = 0;
As you can see, both the move and the copy constructor are deleted, but conveniently, you can still manage to capture the object produced by createOnStack() like so:
Foo && a = Foo::createOnStack();
const Foo& b = Foo::createOnStack();
This allows me to restrict an object of Foo to be constructed on stack only
1) You can only access it via Foo::createOnStack() and only store a const-lvalue or rvalue reference to it.
2) That means it is deconstructed always at the end of the scope at which Foo::createOnStack() was called.
3) Instances are thus always destructed in the reverse order they are constructed
The problem I have is that someone in the comment told me that the standard committee were on their way to make this
new Foo(Foo::createOnStack());
legal code. I advise against it, as this (as shown) may break the consistency of existing code. I'd like to hear your comments about the issue, and if there exists a possibly better maintainable solution to make a class that fulfills (3).