This may sound like a weird question, but I would like to know if it is possible to write a class, such that instances..
- can only be created by means of some
Creator
- cant be copied and no reference to the instance can leave the scope
This is what I tried...
template <typename T>
struct Creator {
T create(){ return T();}
};
struct Foo {
private:
friend class Creator<Foo>;
Foo(){}
void operator&();
Foo(Foo const&);
};
//Foo* foo(){ return &Creator<Foo>().create();} // compiler error
//Foo foo(){ return Creator<Foo>().create();} // compiler error
const Foo& foo(){ return Creator<Foo>().create();} // >>>> BOOM <<<<
Maybe the solution is simple and I just dont get it, but I have no idea how to prevent references binding to instances (or if this is even possible). And I didnt even start to consider moving...
Is is possible to disable instances to leave (by any means) the scope where they were created ?
PS: The class would be used as kind of temporary. Thus I am not too much concerned about something like this:
const Foo& foo(
static Foo f;
return f;
}
because this would mean someone deliberately misused something that was meant for something else. I am more worried about accidental mistakes (eg. dangling references/pointers).