How does the following code exactly work?
#include <cstdio>
template<class T>
T x = T{};
void foo()
{
class Test
{
public:
Test() { std::printf("Test::Test\n"); }
};
Test t = x<Test>;
}
int main()
{
std::printf("main\n");
}
Output
Test::Test
main
- Why does it print
Test::Test
first instead ofmain
? - Which standard it relies on? Is it C++1z only? I can't find the related proposal. Could you give me a link?
- What is
x
in this code and how doesTest t = x<Test>
assignment actually work?
Moreover, if I change std::printf
calls to std::cout
the whole program crashes:
#include <iostream>
template<class T>
T x = T{};
void foo()
{
class Test
{
public:
Test() { std::cout << "Test::Test\n"; }
};
Test t = x<Test>;
}
int main()
{
std::cout << "main\n";
}
Output
Segmentation fault (core dumped) ./a.out
Why?