简体   繁体   中英

Why aren't default parameters fully initialized in Release? (Debug vs. Release)

Just to give some background on me. I'm an experienced C# developer switching to a c++ project. I did c++ for years early in my career but am a bit rusty... With that said. Here's the simplest example I can come up with to show my issue:

#include <vector>
#include <iostream>

using namespace std;

struct Inner
{
public:
    float A;
    unsigned short B;    

    Inner()
        :A(0.0F), B(0)
    {
    }

    Inner(const float& valA, const unsigned short& valB)
        : A(valA), B(valB){}        
};

class Outer
{
private:
    const vector<Inner> CollectionOfInner;

public:
    Outer(const vector<Inner> initialVal = { Inner(1.0F, 4), Inner(9.0F, 4), Inner(81.0F, 18) })
        : CollectionOfInner(initialVal)
    {
        cout << "Values" << '\n';
        for (int i = 0; i < 3; i++)
        {
            cout << "A: " << CollectionOfInner[i].A << " B: " << CollectionOfInner[i].B << '\n';
        }
    }    
};

int main()
{
    Outer test;
}

My program simply creates a stack instance of Outer relying on the default parameter shown above. In debug everything works as expected giving the following output:

Values
A: 1 B: 4
A: 9 B: 4
A: 81 B: 18
Press any key to continue . . .

However, in Release configuration only the first of the three Inner instances is properly initialized and the output is the following:

Values
A: 1 B: 4
A: 4.59009e-039 B: 4138
A: 2.64788e-038 B: 52345
Press any key to continue . . .

I'm sure this has something to do with some optimization that is turned on in release... but for the life of me I can't imagine why you would EVER want this behavior... At first I thought there was just some sort of memory trashing going on in my larger project, but once I confirmed the "bug" with a dirt simple project like this I knew something more fundamental was going on. Note: If I supply a pre-created vector to the Outer constructor everything is fine. The problem appears only when relying on the default constructor. Any Ideas? Also, for reference this is done in Visual Studio 2013 using the standard C++ console application project template.

Consensus seems that this is a bug in Visual Studio 2013. Answering this myself to resolve the question. Thanks everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM