DerGaijin
DerGaijin

Reputation: 31

A Variable changing the output

So i just run a quick example and could use some help understanding what happend

I run the test with the Variable "RandomNumber" commented and the output was

Construct
Invoke
Destruct

So I run the test again but with the Variable "RandomNumber" uncommented and the output was

Construct
Destruct
Invoke

I tried that many times with the same result but i don't really understand why that Variable is changing the lifetime of the Tester...
The Test:

struct Container 
{
    template<typename T>
    Container(T&& O) : Data((void*)std::addressof(O)) {}

private:
    void* Data;
    //std::weak_ptr<int> RandomNumber;
};

struct Tester
{
    Tester() { std::cout << "Construct" << std::endl; }
    ~Tester() { std::cout << "Destruct" << std::endl; }
};

void TestFunction1(const std::vector<Container>& Data)
{
    std::cout << "Invoke" << std::endl;
}

int main()
{
    TestFunction1({ Tester() });
    return 0;
}

Upvotes: 2

Views: 65

Answers (2)

junior_spirit
junior_spirit

Reputation: 21

After testing on multiple configurations the result varies from system to system and compiler to compiler. Hence, it is difficult to predict what the outcome could be.

Upvotes: 1

avr_dude
avr_dude

Reputation: 242

After running the code multiple times on Windows 10, I have observed that it produces almost the same output whether weak_ptr<int> RandomNumber is commented or not:

Construct
Invoke
Destruct

This implies that output differs in systems as other online compilers have produced the same result as you. The most probable reason is the output is system/compiler dependent and the different optimizations the compiler does.

Upvotes: 1

Related Questions