Frontier
Frontier

Reputation: 61

Why does std::vector's constructor calls custom class's destructor?

I made a class what allocates its own memory in the constructor and deallocates it in the destructor. However if i make a std::vector of it like std::vector<CLASS> m(1) its allocated data gets instantly deallocated. That means i lose all the data i assigned in the constructor. How can i prevent this? example:

#include <iostream>
#include <vector>
class test
{
public:
    test()
    {
        std::cout<<"construction of test"<<std::endl;
        std::cout<<"  -MEMORY ALLOCATION"<<std::endl;
    }
    ~test()
    {
        std::cout<<"destruction of test"<<std::endl;
        std::cout<<"  -MEMORY DEALLOCATION"<<std::endl;
    }
};
int main()
{
    std::vector<test> m(1);
    std::cout<<"main"<<std::endl;
    return 0;
}

That code printed out this for me:

construction of test
  -MEMORY ALLOCATION
destruction of test
  -MEMORY DEALLOCATION
main
destruction of test
  -MEMORY DEALLOCATION

I'm using g++ on windows 7 with -Os and -std=c++11 if it is important.

Upvotes: 0

Views: 113

Answers (2)

user2428400
user2428400

Reputation:

As in the code posted by Mooing Duck, you will see a copy happening for the reasons described by A.B.

I'm guessing a little bit as to what you really want to achieve, but if you just want to initialise the vector with a single "test" instance, without copies occurring, then you can use the emplace mechanism in C++11 containers.

int main()
{
    std::vector<test> m();
    m.emplace_back();
    std::cout<<"main"<<std::endl;
    return 0;
}

This should output (assuming a print in the copy constructor, even):

construction of test
  -MEMORY ALLOCATION
main
destruction of test
  -MEMORY DEALLOCATION

emplace_back() constructs the object in-place within the vector, without any copies being made. If your "test" constructor has arguments, then these become the arguments to emplace_back, and will be forwarded on to the constructor, again without copies.

Note: Copies (or moves) can still occur IF the emplace_back causes a reallocation, so for best performance ensure your vector's capacity is enough to contain all of the instances you emplace_back.

Upvotes: 0

A.B.
A.B.

Reputation: 16630

What happens is that a temporary test object is created, copied into the vector, then destroyed. Its copy lives on in the vector until the vector is destroyed.

Upvotes: 1

Related Questions