0

I have declared an static vector inside a class:

class Algorithm
{
private:
    
    const static std::vector<Algorithm> Cancellations;
}

I initialize the vector outside the class:

const std::vector<Algorithm> Algorithm::Cancellations =
{
        Algorithm("F z'"), Algorithm("b"),
        Algorithm("b S"), Algorithm("B"),
        Algorithm("f z'"), Algorithm("B"),
        Algorithm("S b"), Algorithm("B"),
        Algorithm("z' f"), Algorithm("B"),
        Algorithm("f b"), Algorithm("B F"),
        Algorithm("F S"), Algorithm("B z"),
        // Many more algorithms
};

Everything works fine, but I have a warning because this vector is too big for the stack, and suggest me that I should move it to the heap, so I change the declaration:

class Algorithm
{
private:
    
    const static std::vector<Algorithm>* Cancellations;
}

And the initialization:

const std::vector<Algorithm>* Algorithm::Cancellations = new std::vector<Algorithm>
{
        Algorithm("F z'"), Algorithm("b"),
        Algorithm("b S"), Algorithm("B"),
        Algorithm("f z'"), Algorithm("B"),
        Algorithm("S b"), Algorithm("B"),
        Algorithm("z' f"), Algorithm("B"),
        Algorithm("f b"), Algorithm("B F"),
        Algorithm("F S"), Algorithm("B z"),
        // Many more algorithms
};

Everything works fine again, but the warning is still there.

As I read here: When vectors are allocated, do they use memory on the heap or the stack?, if the vector isn't declared static the data should already been stored in the heap in the two cases. Why when I declare a vector static is stored always in the stack? Or I am missundertanding something?

Here is the information about the warning: https://learn.microsoft.com/en-us/cpp/code-quality/c6262?f1url=%3FappId%3DDev16IDEF1%26l%3DES-ES%26k%3Dk(C6262)%26rd%3Dtrue&view=msvc-160

Thank you.

trincot
  • 317,000
  • 35
  • 244
  • 286
GRVigo
  • 43
  • 4
  • 3
    That warning sounds bogus for two reasons: an `std::vector`'s size is constant because its contents are dynamically allocated, and a static class member variable is *not* allocated on the stack anyway... – Quentin Nov 04 '21 at 15:35
  • 2
    "Stack" usage is the `initializer_list`... – Jarod42 Nov 04 '21 at 15:35
  • 2
    It's not complaining about the vector, it is complaining about all of the temporary objects you create in the initializer list. You might need to store this information in a file, and then read in and initialize the vector with those values at run time. – NathanOliver Nov 04 '21 at 15:35
  • 1
    I think that the problem come from the temp objects you're using if it is copied or moved they are on the stack , use heap allocation for them – Anis Belaid Nov 04 '21 at 15:36
  • @NathanOliver What you say makes all the sense. Thank you. – GRVigo Nov 04 '21 at 15:44
  • You could populate it with an immediately-invoked lambda, allowing you to reserve and push-back. – Ben Nov 06 '21 at 00:31

0 Answers0