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)
std::vector<T>::clear() always calls the destructor of each element, but the destructor of a pointer is a no-op (or a pointer has a trivial destructor).
Destructors of Vectors and Strings in C++If you are using std::vector and std::string , the destructor is automatically called when their objects are out of scope. These classes have their destructors implemented which are triggered automatically when their corresponding objects need to be deleted.
An explicit call to destructor is only necessary when an object is placed at a particular location in memory by using placement new. Destructor should not be called explicitly when the object is dynamically allocated because the delete operator automatically calls destructor.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With