0

Code:

#include <iostream>
#include <memory>

class Test {
public:
    void TestFunc() {
        std::cout << "TestFunc()\n";
    }
};

int main() {
    std::unique_ptr<Test> ptr1(new Test);
    ptr1->TestFunc();

    std::unique_ptr<Test> ptr2 = std::move(ptr1);
    ptr2->TestFunc();

    if (ptr1 == nullptr) {
        std::cout << "Now ptr1 is nullptr\n";
    }

    ptr1->TestFunc(); // !!
}

Result:

TestFunc()
TestFunc()
Now ptr1 is nullptr
TestFunc() // !!

Like above code, the ownership of Test object is moved from ptr1 to ptr2.

However, still I can call TestFunc() through ptr1 even though ptr1 has confirmed as nullptr after moving. How is this possible?

EnDelt64
  • 1,270
  • 3
  • 24
  • 31
  • @NathanOliver thanks for adding it as a duplicate – KostasRim Apr 15 '19 at 14:00
  • 2
    Your function is not virtual, does not access this pointer, so the compiler just generate the call with a this pointer to null ... that's all. – Gojita Apr 15 '19 at 14:00
  • Dereferencing a `nullptr` is undefined behavior. So basically, everything can happen. Maybe your compiler spilled the same address for the pointer stored in `ptr1` assuming "something". Noone can actually exactly tell, because it is undefined. – UniversE Apr 15 '19 at 14:00
  • Thanks for the answer. This code works same in gcc and msvc so I thought it is a standard behavior. – EnDelt64 Apr 15 '19 at 14:01
  • What @Gojita said: https://ideone.com/43YeUx (even tho, yes, it is UB). – Mirko Apr 15 '19 at 14:58

0 Answers0