In C++ (I use QT) I can create an instance of QString class two ways:
QString str = "my string";
QString *str = new QString("my string");
I know this is to do with pointers. So my questions are:
delete str;
. How can I delete the str
variable when using method 1?Thanks
Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.
Declaring an Object name is the name to be used for the variable. Declarations simply notify the compiler that you will be using name to refer to a variable whose type is type. Declarations do not instantiate objects. To instantiate a Date object, or any other object, use the new operator.
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With