سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

I would suggest replacing the for loop. I don't trust for loops. Too many places for bugs to creep in.

std::vector<A>& v = Get();
x.insert(x.end(), v.begin(), v.end());

There are only two possibilities - the reference is bad, or the object itself is bad.

Since the reference is to a static vector, it doesn't seem possible that the reference could be bad. Static objects don't go away.

That leaves the object itself. Is it possible that the function is being called before the static object is initialized? This could happen if it were being called from the constructor of another static object.

It is incorrect only if some_object lifetime is restricted to the body of Get.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top