0

String variable still working after the destructor is called.

So, I have this code

#include<iostream>
#include<string>
using str = std::string;

int main(){
    str x;
    x = "Hi";
    x.~str();

    std::cout << x;
}

And it works, which i don't expect it to. Can anyone explain why is that so? Also, it throws up this runtime error when i make the string longer free(): double free detected in tcache 2

I know explicitly calling the destructor is not recommended, but i am curious what's happening here both times (when it runs and when it errors out and why are there two outcomes depending on the length of string), (i suspect there is SSO is at work here)

  • 2
    Undefined Behaviour includes appearing to work (until it doesn't). Double destruct _"...Note that calling a destructor directly for an ordinary object, such as a local variable, invokes undefined behavior when the destructor is called again, at the end of scope...."_ https://en.cppreference.com/w/cpp/language/destructor and Lifetime _"...The lifetime of an object ends when:...if it is of a class type, the destructor call starts..."_ https://en.cppreference.com/w/cpp/language/lifetime – Richard Critten Oct 29 '22 at 17:13
  • 1
    What were your expectations and why? – al3c Oct 29 '22 at 17:14
  • It's UB but what happens varies with compilers. MSVC releases any dynamic memory and resets the object to a 0 length string. GCC just releases any dynamic memory. As a result MSVC's UB doesn't cause a problem but GCC's does as it will try to release the memory again once out of scope. That's why it's called UB. In the example, SSO means no dynamic memory was used so can seem safe. – doug Oct 29 '22 at 17:16
  • I was just testing something out with no real intent. Just wanted to know why it works with short string but not with longer ones. – RoyKin00 Oct 29 '22 at 17:17
  • 3
    @RoyKin00: It's really important to understand this: C++ is *not a safe language*. You cannot learn it by trying random stuff and assuming that if the compiler doesn't stop you and it seems to work, then you're doing the right thing. – Nicol Bolas Oct 29 '22 at 17:18
  • @RoyKin00 *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB. The program may just crash."* – Jason Oct 29 '22 at 17:23

0 Answers0