Now, I assume we have a dangling pointer, so what is the correct way of writing this code so that there is nothing wrong, please? |
You still do not have a dangling pointer. You do have a memory leak, though, whenever an instance of class
Test
is destroyed. When the instance of class
Test
is destroyed, the pointer myPtr is also destoyed, and if a pointer doesn't even exist, it can't be a dangling pointer.
so what is the correct way of writing this code so that there is nothing wrong, please? |
Best; just don't use dynamic memory.
1 2 3 4 5 6 7 8 9
|
class Test {
int myInt;
public:
Test(int& i): {
myInt = i;
}
void print() { cout << myInt << endl; }
};
| |
If you HAVE to use dynamic memory - for example, you're making a really big object, then use modern C++ smart pointers. You wouldn't do this for an
int, but for the purposes of an example:
1 2 3 4 5 6 7 8 9 10 11
|
class Test
{
std::unique_ptr<int> myPtr;
public:
Test(int& i)
{
myPtr = std::make_unique<int>(i);
}
void print() { std::cout << *myPtr << std::endl; }
};
| |
A unique_ptr will, when it is destroyed, call delete for you on the object it is pointing at. The memory is released properly and there is no leak.
For the purposes of learning, using new and delete:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class Test
{
int* myPtr;
public:
Test(int& i)
{
myPtr = new int (i);
}
void print() { std::cout << *myPtr << std::endl; }
~Test()
{
delete myPtr; // prevent memory leak
}
};
| |
I know that you're just experimenting for learning purposes, but it's still worth saying this; ising new and delete manually is bad. Don't do it. If you find yourself typing new or delete, stop. This is C++ in the year 2019; we have smart pointers and containers and so on. Manual memory management in new code is a sign that something has gone wrong.
But the question is, what does that default constructor do on our pointer ptr in the class, please. |
Nothing. You get a pointer, with no guarantees whatsoever about where it is pointing.