Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the right way to instantiate objects in C++?

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:

  1. what is the difference between the two?
  2. which method should I stick to?
  3. when is it correct to use method 1 and when is it correct to use method 2?
  4. in method 2 I can destroy the object by calling delete str;. How can I delete the str variable when using method 1?

Thanks

like image 343
Roman Avatar asked Dec 09 '11 01:12

Roman


People also ask

How do we instantiate an object?

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.

How do you declare and instantiate an object?

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.

What operator is used to instantiate an object?

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.


1 Answers

  1. 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.

  2. 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.

  3. 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)

  4. in method 1 the object will be automatically deleted when the function returns.

like image 121
necromancer Avatar answered Sep 21 '22 12:09

necromancer