0

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).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 2
    No. You can't stop someone from declaring a static instance and returning a reference to it. – NathanOliver May 23 '17 at 20:15
  • A bit of a similar thing: https://stackoverflow.com/questions/27492132/how-can-i-remove-refactor-a-friend-dependency-declaration-properly But as @Nathan said, you can't prevent this. – πάντα ῥεῖ May 23 '17 at 20:18
  • In your example, the instance does not leave the scope -- you just create a dangling reference to the memory used by the instance after it is destroyed. Which is bad, but for completely different reasons. – Chris Dodd May 23 '17 at 20:21
  • 1
    I have a feeling you are dealing with [a XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – R Sahu May 23 '17 at 20:22
  • @ChrisDodd I know, it is a bad example, because anyhow one shouldnt do this. I just wanted to keep it simple. Think of something more contrived, e.g. a different object that keeps a reference to `Foo` and gets returned by value from `foo` – 463035818_is_not_an_ai May 23 '17 at 20:23
  • @RSahu I can understand why you think so, but it turns out that I am really more interested in the Y than the X and I believe Y in itself is worth an answer, even if the answer is "no you cant" – 463035818_is_not_an_ai May 23 '17 at 20:25

0 Answers0