开发者

Is STL Vector calling a destructor of a not-allocated object?

开发者 https://www.devze.com 2023-04-08 14:24 出处:网络
The folowing code shows an output not expected: class test { public: test() { 开发者_运维问答std::cout << \"Created\" << (long)this << std::endl;

The folowing code shows an output not expected:

class test
{
    public:
    test()
    {
   开发者_运维问答     std::cout << "Created" << (long)this << std::endl;
    }
    ~test()
    {
        std::cout << "Destroyed" << (long)this << std::endl;
    }
};

int main(int argc, char** argv)
{
    std::vector<test> v;
    test t;
    v.push_back(t);

    return EXIT_SUCCESS;
}

When executed it shows:

Created-1077942161
Destroyed-1077942161
Destroyed674242816

I think the second "Destroyed" output should not be there. When I don't use the vector the result is one Created and one Destroyed line as expected. Is this behavior normal?

(This is compiled with GCC on a FreeBSD system)


Everything is as it should be: there's the local variable t, which gets created and then destroyed at the end of main(), and there's v[0], which gets created and destroyed at the end of main().

You don't see the creation of v[0] because that happens by copy or move constructor, which your test class doesn't provide. (So the compiler provides one for you, but without output.)


For testing purposes it's handy to write for yourself once and for all a test class that contains all the possible constructors, destructors, assignment and swap operators and prints a diagnostic line in each, so you can witness how objects behave when used in containers and algorithms.


#include <cstdlib>
#include <vector>
#include <iostream>

class test
{
    public:
    test()
    {
        std::cout << "Created " << (long)this << std::endl;
    }
    test( const test& )
    {
        std::cout << "Copied " << (long)this << std::endl;
    }
    ~test()
    {
        std::cout << "Destroyed " << (long)this << std::endl;
    }
};

int main(int argc, char** argv)
{
    std::vector<test> v;
    test t;
    v.push_back(t);

    return EXIT_SUCCESS;
}

Output:

Created -1076546929
Copied 147865608
Destroyed -1076546929
Destroyed 147865608

std::vector::push_back copies the t object, you can see the copy constructor being invoked by the above code.


The vector is holding a copy of t, therefore after the call to push_back, you have two versions of t ... one on the stack, and one in the vector. Since the vector version was created by a copy-construtor, you don't see a "Created ..." prompt for that object ... but it still must be destroyed when the vector container goes out of scope, therefore you get two "Destroyed ..." messages.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号