I’m a python programmer who sees a lot of C++ code but doesn’t know the language and there seems to be two ways to initalize a class. I was hoping that someone can tell me the difference.
class Point {
int x, y;
public:
int get_x();
int get_y();
Point(int, int);
}
// ok we are going to leave the methods and constructors unimplemented for brevity
// now here's the part that puzzles me
Point p(5, 5); // ..or
Point p = new Point(5, 5);
What’s the diffrence between the two?
One of those variables lives on the stack, the other on the heap. The correct syntax is this:
Point p(5, 5);
Point* p = new Point(5, 5);
The first one creates an object on the stack. When p goes out of scope, it’ll be removed automatically. The second, creates a point object on the heap. Until you remove it manually, it’ll remain in memory.
In the second case, p is a pointer to the Point object, while in the first case p is the point object.
Python essentially does only the second version and doesn’t do the first. Python is garbage collected, so it’ll also remove the point object from memory if it is no longer referenced.
However, I should mention (see comments) that the prefered method to create objects on the heap is to use smart pointers. See DeadMG’s answer for more details.
15
Point p(5, 5); // ..or
Creates an automatic variable “on the stack”. This means that it’s lifetime and memory is fixed to it’s scope.
Point* p = new Point(5, 5);
Creates a memory leak, double delete, or heap corruption in your program. This means that it almost certainly will crash your program, cause it to corrupt user data, or other fun side effects. Which is why actual C++ programmers use alternatives, such as…
auto p = make_unique<Point>(5, 5);
Creates a Point “on the heap”. In this case, it’s lifetime and memory is fixed to the lifetime of the owning unique_ptr<Point>
. This ownership can be transferred by move semantics. Unfortunately, make_unique
is not provided as Standard (a known defect) but it’s relatively easy to roll your own. It is a simple factory function.
auto p = std::make_shared<Point>(5, 5);
Also creates a Point “on the heap”. In this case, it’s lifetime and memory is fixed to the lifetime of each shared_ptr<Point>
that points to it. When they are all destroyed, the Point
will be cleaned up. shared_ptr<Point>
can be copied, unlike unique_ptr<Point>
. This is very similar to Python’s behaviour. However, do not forget that unlike in Python, there will be no machinery to break reference cycles.
9