2

I have created a pointer p of class A type after moving the pointer also I am able to make a call to class A function.

Looking for a proper explanation of this

class A {
public:
    void print() {
        std::cout << "hello";
    }

};

int main() {
    std::shared_ptr<A> p ( new A);
    auto p2 = std::move(p);
    p->print();

}

User
  • 572
  • 2
  • 10
  • 3
    https://stackoverflow.com/questions/11320822/why-does-calling-method-through-null-pointer-work-in-c <- explanation to your issue. If you want to trigger crash of your app, add some data member to your class, and write it in `print`. Then, you will see segfault. – rafix07 Jan 14 '22 at 11:16
  • 1
    The function is part of the class and not of the instance. As long the member function never access any member data, it is as long it is not a volatile function the same as calling a static function. Think the other way around: If you can make the function static without changing anything else of your code, the method is not related to any object of the class. – Klaus Jan 14 '22 at 11:25
  • 2
    One of the many faces of undefined behaviour is "the program does something apparently sensible instead of crashing". – n. m. could be an AI Jan 14 '22 at 12:01
  • Unfortunately move() does not assign nullptr to p, so this is the C++ version of use-after-free. – U. W. Jan 14 '22 at 12:24
  • 1
    Even though `std::move` doesn't reset `p`, `shared_ptr`'s move constructor does. So when `p2` grabs the pointer, it also nulls `p`. – BoP Jan 14 '22 at 12:45
  • It works exactly like `A* p = new A; A* p2 = p; p = nullptr; p->print();`. That is, it is undefined. It only appears to work because `print` does not access any members. – molbdnilo Jan 14 '22 at 13:25
  • @rafix07 "*If you want to trigger crash of your app, add some data member to your class, and write it in `print`. Then, you will see segfault.*" - that is not guaranteed. The code has *undefined behavior *, so literally ANYTHING can happen, including a segfault, but also NOT a segfault, too – Remy Lebeau Jan 15 '22 at 07:57

0 Answers0