I\'m coming from a Java background and have started working with objects in C++. But one thing that occurred to me is that people often use pointers to objects rather than t
Well the main question is Why should I use a pointer rather than the object itself? And my answer, you should (almost) never use pointer instead of object, because C++ has references, it is safer then pointers and guarantees the same performance as pointers.
Another thing you mentioned in your question:
Object *myObject = new Object;
How does it work? It creates pointer of Object
type, allocates memory to fit one object and calls default constructor, sounds good, right? But actually it isn't so good, if you dynamically allocated memory (used keyword new
), you also have to free memory manually, that means in code you should have:
delete myObject;
This calls destructor and frees memory, looks easy, however in big projects may be difficult to detect if one thread freed memory or not, but for that purpose you can try shared pointers, these slightly decreases performance, but it is much easier to work with them.
And now some introduction is over and go back to question.
You can use pointers instead of objects to get better performance while transferring data between function.
Take a look, you have std::string
(it is also object) and it contains really much data, for example big XML, now you need to parse it, but for that you have function void foo(...)
which can be declarated in different ways:
void foo(std::string xml);
In this case you will copy all data from your variable to function stack, it takes some time, so your performance will be low.void foo(std::string* xml);
In this case you will pass pointer to object, same speed as passing size_t
variable, however this declaration has error prone, because you can pass NULL
pointer or invalid pointer. Pointers usually used in C
because it doesn't have references.void foo(std::string& xml);
Here you pass reference, basically it is the same as passing pointer, but compiler does some stuff and you cannot pass invalid reference (actually it is possible to create situation with invalid reference, but it is tricking compiler).void foo(const std::string* xml);
Here is the same as second, just pointer value cannot be changed.void foo(const std::string& xml);
Here is the same as third, but object value cannot be changed.What more I want to mention, you can use these 5 ways to pass data no matter which allocation way you have chosen (with new
or regular).
Another thing to mention, when you create object in regular way, you allocate memory in stack, but while you create it with new
you allocate heap. It is much faster to allocate stack, but it is kind a small for really big arrays of data, so if you need big object you should use heap, because you may get stack overflow, but usually this issue is solved using STL containers and remember std::string
is also container, some guys forgot it :)