Search code examples
c++referencetemporary

is this use of references incorrect?


I have the folowing code :

std::vector<A>& Get() { return some_object; };

for(int i=0; i<Get().size(); ++i) {
    x->push_back(Get()[i]);
}

But I'm getting garbage values when I first call size(). I'm thinking that some temporary is deleted somewhere but I'm not really sure... can someone tell me what's happening?

edit : my some_object is a static vector so it's never deleted during this example


Solution

  • If your for loop is being executed from within the context of a global or static object's constructor, then you'll encounter a problem called static initialization order fiasco (SIOF). In a nutshell, SIOF means that we can't rely on the order that static objects will be constructed.

    To get around this problem, you can use the construct on first use idiom. With this idiom, you construct static/global objects lazily the first time they are needed. This ensures that static objects that depend on one another will be created when they are accessed.

    For your example, you could do something like this:

    std::vector<A>& Get()
    {
        // 'instance' will be constructed "on demand" the first time this
        // function is called.
        static std::vector<A> instance;
        return instance;
    };
    

    This trick is also used to implement the Singleton design pattern.

    NOTE: If your program is multi-threaded, you have to use a variant of this trick.