I recently started learning about smart pointers and move semantics in C++. But I can't figure out why this code works. I have such code:
#include <iostream>
#include <memory>
using namespace std;
class Test
{
public:
Test()
{
cout << "Object created" << endl;
}
void testMethod()
{
cout << "Object existing" << endl;
}
~Test()
{
cout << "Object destroyed" << endl;
}
};
int main(int argc, char *argv[])
{
Test* testPtr = new Test{};
{
unique_ptr<Test> testSmartPtr(testPtr);
}
testPtr->testMethod();
return 0;
}
My output is:
Object created
Object destroyed
Object existing
Why does row testPtr->testMethod()
work? Doesn't unique_ptr delete the pointer assigned to it on destruction if the pointer is an lvalue?
Edit: I learned from the comments that this method doesn't check if the pointer exists. If so, is there a way to check if the pointer is valid?
Edit: I learned that I shouldn't do anything with invalid pointers. Thank you for all your answers and comments.
Edit: Even this code works:
#include <iostream>
#include <memory>
using namespace std;
class Test
{
public:
Test(int num) :
number{ num }
{
cout << "Object created" << endl;
}
void testMethod(int valueToAdd)
{
number += valueToAdd;
cout << "Object current value: " << number << endl;
}
~Test()
{
cout << "Object destroyed" << endl;
}
private:
int number;
};
int main(int argc, char *argv[])
{
Test* testPtr = new Test(42);
{
unique_ptr<Test> testSmartPtr(testPtr);
}
testPtr->testMethod(3);
return 0;
}
I think it's because the compiler optimized it. Anyway, I really shouldn't do anything with invalid pointers.