VC compiler bug ?

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
 
W

William M. Miller

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top