VC compiler bug ?

  • Thread starter Thread starter Ares Lagae
  • Start date Start date
A

Ares Lagae

Consider this code fragment:


#include <iostream>

template <class T>
class Foo
{
public:
T m_f;
Foo(T f) : m_f(f) {}
//Foo(const Foo & foo) : m_f(foo.m_f) {}
static const Foo CONST;
};

template <class T>
const Foo<T> Foo<T>::CONST = Foo(T(1));

class Bar
{
public:
Foo<float> m_foo;
Bar() : m_foo(Foo<float>::CONST)
{
std::cout << "Foo.m_f = " << m_foo.m_f << std::endl;
}
};

Bar bar;

int main(int argc, char * argv[])
{
Bar bar;
return 0;
}

When executed, it prints

Foo.m_f = 0
Foo.m_f = 1

but according to the c++ standard, (i think) it should print

Foo.m_f = 1
Foo.m_f = 1

strangly, when the copy constructor

//Foo(const Foo & foo) : m_f(foo.m_f) {}

is uncommented, it prints

Foo.m_f = 1
Foo.m_f = 1


Is this a bug ?


Best regards,
Ares Lagae
 
Ares Lagae said:
Consider this code fragment:


#include <iostream>

template <class T>
class Foo
{
public:
T m_f;
Foo(T f) : m_f(f) {}
//Foo(const Foo & foo) : m_f(foo.m_f) {}
static const Foo CONST;
};

template <class T>
const Foo<T> Foo<T>::CONST = Foo(T(1));

class Bar
{
public:
Foo<float> m_foo;
Bar() : m_foo(Foo<float>::CONST)
{
std::cout << "Foo.m_f = " << m_foo.m_f << std::endl;
}
};

Bar bar;

int main(int argc, char * argv[])
{
Bar bar;
return 0;
}

When executed, it prints

Foo.m_f = 0
Foo.m_f = 1

but according to the c++ standard, (i think) it should print

Foo.m_f = 1
Foo.m_f = 1

strangly, when the copy constructor

//Foo(const Foo & foo) : m_f(foo.m_f) {}

is uncommented, it prints

Foo.m_f = 1
Foo.m_f = 1


Is this a bug ?

No. The reason that you can get 0 for the global bar
is that initialization of static members of class
templates is unordered with respect to other static
initialization. However, static initialization is
complete before main() begins execution, so the local
bar is initialized with the initialized version of
CONST. I'm not sure why having a user-defined copy
constructor would change the order, but both orders are
Standard-conforming.

-- William M. Miller
 
Back
Top