Why double destructor call | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

Why double destructor call

What's wrong in this code ? Why two times destructor is called ? https://code.sololearn.com/cYBe2NnYd4Ek/?ref=app

21st Sep 2023, 6:10 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
5 ответов
+ 2
statement < myString(); > on line 18, does not call < myString::myString() > on the <this> object, instead it would construct a temporary local object ( this temporary object has nothing common with the object created by constructor < myString::myString(char const*) > ), which will then be instantly deleted at the end of the statement. ( hence the first call to the destructor ). you can use delegating constructor (since C++11) to rewrite your class the following way: https://www.sololearn.com/compiler-playground/c26P1AaheI2y
22nd Sep 2023, 2:17 PM
MO ELomari
+ 1
It’s called twice because the overloaded constructor creates a new myString object if pInput is a nullptr. In main you defined char* p to nullptr then called myString’s overloaded constructor by passing p as a parameter - this created the new myString object using the default constructor - hence the destructor ran twice. Once for both instances of myString.
22nd Sep 2023, 1:38 AM
DinoBambino
+ 1
In the overloaded constructor, Initialize your member variables to the same values used in the default constructor. You can change the condition in the overloaded constructor to check if the parameter passed is not a nullptr & perform the appropriate steps. That way you don't have to do anything if a nullptr is passed. The member variables are already initialized just as if you had called the default constructor. I updated your code to clarify what I mean: https://www.sololearn.com/compiler-playground/cUozOMz4FI0i
22nd Sep 2023, 5:49 AM
DinoBambino
0
Great. I missed that part. Got idea like two constructor call resulting into two destructors. Just curious to know whether there is any mechanism which avoid this ? In other words, how to delegate to empty constructor if we have nullptr?
22nd Sep 2023, 3:56 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Thanks a ton..!
22nd Sep 2023, 2:42 PM
Ketan Lalcheta
Ketan Lalcheta - avatar