Incomplete object creation and output behavior

How does the following code 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

Living example

  • Why print Test::Testfirst instead main?
  • What standard does he use? Is it just C ++ 1z? I can not find the appropriate offer. Could you give me a link?
  • What is xin this code and how is the assignment really fulfilled Test t = x<Test>?

Also, if I change the std::printfcalls to std::cout, the whole program will work:

#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

Real time example

Why?

+4
source share
1 answer

As mentioned earlier, you used a variable template.

If I am not mistaken, variable templates are similar to the following:

template<class T>
struct X {
    static T x;
};

template<class T>
T X<T>::x = T{};

, :

void foo() {
    class Test {
    public:
        Test() { std::printf("Test::Test\n"); }
    };

    Test t = X<Test>::x;
}

, : coliru.

foo, . main, Test::Test.

, , , , , foo , Test , foo, X<Test>::x - ...

... , , , .

, , / , .

+3

All Articles