473,657 Members | 2,499 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multiple destructors called in relation of vector<> structure

14 New Member
I am not able to understand why the 2nd ~Test() is called with different 'this' but the same string value ??
Also why does it give error, if I want to declare Test::Str as a const string member ??

Expand|Select|Wrap|Line Numbers
  1. =======================================================
  2. struct Test{
  3.   string Str;  // Gives error if, you declare const string !
  4.   Test(const string s) : Str(s) { cout<<Str<<"  Test() "<<this<<endl; }
  5.  ~Test()                               { cout<<Str<<" ~Test() "<<this<<endl; }
  6. };
  7.  
  8. struct TestWrapper{
  9.   vector<Test> vObj;
  10.   TestWrapper(const string s) {  vObj.push_back(s); }
  11.  ~TestWrapper() { }
  12. };
  13.  
  14. int main ()
  15. {
  16.   TestWrapper obj("HELLO");
  17. }
  18.  
  19. Output:
  20. ======
  21. HELLO  Test() 0x7fbffff700
  22. HELLO ~Test() 0x7fbffff700
  23. HELLO ~Test() 0x503040      <------- Why ? 
  24. =======================================================
Dec 25 '09 #1
4 2478
prasoonsaurav
3 New Member
string Str; // Gives error if, you declare const string !
This is because std::vector requires its objects to be assignable. Declaring your string as "const" won't allow assignment operation to be performed on the vector object.

I am not able to understand why the 2nd ~Test() is called with different 'this' but the same string value ??
vObj.push_back( s);involves an implicit cast of s to Test. So what's actually happening is vObj.push_back( Test(s)); and the temporary object gets destroyed after it is copied into the vector.

The object within the vector is constructed using a copy constructor (not the (const string s) constructor) which is why you don't see any constructor call corresponding to the destructor call.
Try adding a copy constructor to your Test:
Expand|Select|Wrap|Line Numbers
  1.  
  2. Test(const Test &obj)
  3.     cout<<obj.Str<<" Test() "<<this<<endl;
  4.     Str = obj.Str;
  5. }
  6.  
  7.  
You'll see the copy constructor being called as well, this call happens at the time the object is being put in the vector. So we have two calls to constructors and two calls to destructor.
Dec 25 '09 #2
Savage
1,764 Recognized Expert Top Contributor
It's because of this:

Expand|Select|Wrap|Line Numbers
  1.  TestWrapper(const string s) { vObj.push_back(s); }
vObj is vector of type Test, but you are pushing a string into it, so implicit conversion happens because your Test has constructor which accepts string as a argument, therefore another Test instance is created and filled with text "HELLO" and thats the first line of your output.But the temporary that was created on stack inside the TestWrapper(con st string) has to be destroyed before the function ends, hence the first destructor call.

The second call occurs when ~TestWrapper() gets called hence destroying the vObj, which in turns call destructors of its each member, there is one so another destructor is called and thats it.
Dec 25 '09 #3
iammilind
14 New Member
Thanks for your replies to both.
Is there any logical need to reconstruct the object. vector<> class is optimized, then why such multiple constructors are required ? Any idea.
Because, if you don't have copy constructor or assignment operator, it might be hazardous like following:
=============== =============== =============== ===
struct Test{
int *ptr;
Test(int* const p) : ptr(p) { }
~Test( ) { delete ptr; } // Surely a double delete crash !!
};

int main( )
{
vector<Test> vObj; vObj.push_back( Test(new int));
}

=============== =============== =============== ===
Dec 26 '09 #4
prasoonsaurav
3 New Member
Is there any logical need to reconstruct the object. vector<> class is optimized, then why such multiple constructors are required ?
Frankly speaking there is no logical need to reconstruct the object but that's how C++ is designed to work.

Because, if you don't have copy constructor or assignment operator, it might be hazardous like following:
=============== =============== =============== ===
struct Test{
int *ptr;
Test(int* const p) : ptr(p) { }
~Test( ) { delete ptr; } // Surely a double delete crash !!
};

int main( )
{
vector<Test> vObj; vObj.push_back( Test(new int));
}
In cases where dynamic memory allocation is performed even though compiler will provide a copy constructor and assignment operator, the memory must be allocated and deallocated manually(so you have to write your version of copy constructor and assignment operator considering dynamic memory allocation).

Your above program invokes 'Undefined Behavior' because you are calling "delete ptr" but memory has not been allocated to 'ptr' by default in the copy constructor, thus crashing your application. So its better that you write a copy constructor yourself and allocate memory to 'ptr' inside it.

Remember in your earlier case where you have used vector, you need not take care of the memory allocation and deallocation.
Dec 26 '09 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2260
by: Marc Schellens | last post by:
my dinkumware docu says, vector<...>::rbegin() returns an iterator which points just BEYOND the end of the controlled sequence. Is that true? so I cannot say: for( riter i=v.rbegin(); i != v.rend(); i++) { something = (*i); }
2
6743
by: john smith | last post by:
Hi, when there is a vector<> of pointers to some objects, does calling resize cause vector to call delete on each object, or is there a memory leak problem? for example: struct base {//some vars; ~base();}; vector<base*> vb; vb.push_back(new base); vb.push_back(new base);
10
7066
by: Stefan Höhne | last post by:
Hi, as I recon, std::vector::clear()'s semantics changed from MS VC++ 6.0 to MS' DOT.NET - compiler. In the 6.0 version the capacity() of the vector did not change with the call to clear(), in DOT.NET the capacity() is reduced to 0.
6
3772
by: Joe | last post by:
I have a: vector<string> which contains a few dozen elements. I want to find the index of the element containing a certain string. for example: vector<string> strings; strings.push_back("abc"); strings.push_back("xyz"); strings.push_back("lmnop");
4
2338
by: Anu | last post by:
Hi, We have a class that has its own overloaded operator new and whose prototype seems to correspond to the standard placement new :- class AppClass { public: operator new (size_t size, void *ctx)
5
1951
by: Numeromancer | last post by:
From the C++-FAQ Lite: http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3 ---------------------------- 34.3] Is the storage for a std::vector<Tguaranteed to be contiguous? Yes. This means you the following technique is safe: #include <vector>
8
3608
by: jacek.dziedzic | last post by:
Hi! I need to be able to track memory usage in a medium-sized application I'm developing. The only significant (memory-wise) non- local objects are of two types -- std::vector<and of a custom class simple_vector<that is a hand-rolled substitute for array<>. With the latter I have code that tracks all allocations and destructions, so I can account for all the memory. The question is about std::vector<-- how can I track memory usage
3
5636
by: Rune Allnor | last post by:
Hi folks. I have a function that takes an element in a vector as argument. The naive interface goes as float computeSomething(const std::vector<float>& v, size_t i) { size_t j = i-1; size_t k = i+1;
1
2521
by: iammilind | last post by:
In one of my code, I was using vector<> for certain class. In one of my struct, I have 'const' member data. However, vector<>::clear() throws compile error with that: =========================================== struct Test { const string Str; Test(const string str) : Str(str) {} }; struct TestWrapper
0
8397
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8310
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8827
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7333
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4315
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2731
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1620
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.