Answer the question
In order to leave comments, you need to log in
Why is it possible to access an object through a pointer with a nullptr value?
#include <iostream>
#include <memory>
class Printer
{
public:
void print(std::string text)
{
std::cout << text << std::endl;
}
};
int main()
{
auto printer1 = std::make_unique<Printer>();
std::unique_ptr<Printer> printer2 = std::move(printer1);
if (printer1 == nullptr) {
printer1->print("Printer1 is null!");
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
A class method under the hood is a function that, in addition to the prescribed parameters, is passed a pointer to an object. In your case nullptr is being passed. But the function itself does not refer to the object, and it does not have any data members either. So everything works more or less. But this is UB and could not be lucky. Due to optimizations, the compiler could break something.
Ps The above does not apply to virtual functions. There, the pointer to the function is stored in the vtable in the class instance and the call via nullptr is likely to fail.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question