In C++ (I use QT) I can create an instance of QString class two ways:
method 1
QString str = "my string";
method 2
QString *str = new QString("my string");
I know this is to do with pointers. So my questions are:
- what is the difference between the two?
- which method should I stick to?
- when is it correct to use method 1 and when is it correct to use method 2?
- in method 2 I can destroy the object by calling
delete str;. How can I delete thestrvariable when using method 1?
Thanks
primarily they have different lifetimes: the object created in method 2 will live arbitrarily long until you call delete; in method 1 it will be created on the stack and be destroyed upon return from the function call (if any). secondarily method 2 requires more work because of non-trivial memory management.
use the method that matches the lifetime you want. if the lifetime of method 1 is good enough for you do not use method 2 because it entails the overhead of memory management. if you can restructure your program so that you can do with method 1 while also improving on the design, that will be more efficient and elegant.
see 2. above. in particular, using method 1 and storing a pointer to the object and accessing it after its lifetime is a pitfall. this is also possible with method 2 but the explicit destruction focuses the programmer’s attention on it (but still because the lifetime is not straightforward it is a likely pitfall) a pitfall with method 2 is forgetting to delete it causing a memory leak (or deleting it too early and referring to it as described earlier in this paragraph)
in method 1 the object will be automatically deleted when the function returns.