Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the lifecycle of a C++ object?

I'm a seasoned C developer who is just now getting into C++, and I must admit, I'm very confused about how many ways there are to create, retain, and destroy C++ objects. In C, life is simple: assignment with = copies on the stack, and malloc/free manage data on the heap. C++ is far from that, or so it seems to me.

In light of that, here are my questions:

  1. What are all the ways to create a C++ object? Direct/copy constructor, assignment, etc. How do they work?
  2. What are all the different initialization syntaxes associated with all these types of object creation? What's the difference between T f = x, T f(x);, T f{x};, etc.?
  3. Most importantly, when is it correct to copy/assign/whatever = is in C++, and when do you want to use pointers? In C, I got very used to throwing pointers around a lot, because pointer assignment is cheap but struct copying is less so. How do C++'s copy semantics affect this?
  4. Finally, what are all these things like shared_ptr, weak_ptr, etc.?

I'm sorry if this is a somewhat broad question, but I'm very confused about when to use what (not even mentioning my confusion about memory management in collections and the new operator), and I feel like everything I knew about C memory management breaks down in C++. Is that true, or is my mental model just wrong?

To sum things up: how are C++ objects created, initialized, and destroyed, and when should I use each method?

like image 881
Alexis King Avatar asked Jun 15 '13 07:06

Alexis King


People also ask

What is the life cycle of an object?

We can break the life of an object into three phases: creation and initialization, use, and destruction. Object lifecycle routines allow the creation and destruction of object references; lifecycle methods associated with an object allow you to control what happens when an object is created or destroyed.

What is object life cycle in C#?

Object lifetime is the time when a block of memory is allocated to this object during some process of execution and that block of memory is released when the process ends.

What is the final state in an object life cycle?

You can add, edit, or delete lifecycle states. Final State: Click this button to designate a selected lifecycle state that generally indicates that a Business Object record has completed its lifecycle. Common values include Closed, Retired, or Completed.

How is object created in C?

Create an Object In C++, an object is created from a class. We have already created the class named MyClass , so now we can use this to create objects. To create an object of MyClass , specify the class name, followed by the object name.


2 Answers

First of all, your memory management skills are useful in C++, just they are a level below the C++ way of doing things, but they are there...

About your questions, they are a bit broad, so I'll try to keep it short:

1) What are all the ways to create a C++ object?

Same as C: they can be global variables, local automatic, local static or dynamic. You may be confused by the constructor, but simply think that every time you create an object, a constructor is called. Always. Which constructor is simply a matter of what parameters are used when creating the object.

Assignment does not create a new object, it simply copies from one oject to another, (think of memcpy but smarter).

2) What are all the different initialization syntaxes associated with all these types of object creation? What's the difference between T f = x, T f(x);, T f{x};, etc.?

  • T f(x) is the classic way, it simply creates an object of type T using the constructor that takes x as argument.
  • T f{x} is the new C++11 unified syntax, as it can be used to initialize aggregate types (arrays and such), but other than that it is equivalent to the former.
  • T f = x it depends on whether x is of type T. If it is, then it equivalent to the former, but if it is of different type, then it is equivalent to T f = T(x). Not that it really matters, because the compiler is allowed to optimize away the extra copy (copy elision).
  • T(x). You forgot this one. A temporary object of type T is created (using the same constructor as above), it is used whereever it happens in the code, and at the end of the current full expression, it is destroyed.
  • T f. This creates a value of type T using the default constructor, if available. That is simply a constructor that takes no parameters.
  • T f{}. Default contructed, but with the new unified syntax. Note that T f() is not an object of type T, but instead a function returning T!.
  • T(). A temporary object using the default constructor.

3) Most importantly, when is it correct to copy/assign/whatever = is in C++, and when do you want to use pointers?

You can use the same as in C. Think of the copy/assignment as if it where a memcpy. You can also pass references around, but you also may wait a while until you feel comfortable with those. What you should do, is: do not use pointers as auxiliary local variables, use references instead.

4) Finally, what are all these things like shared_ptr, weak_ptr, etc.?

They are tools in your C++ tool belt. You will have to learn through experience and some mistakes...

  • shared_ptr use when the ownership of the object is shared.
  • unique_ptr use when the ownership of the object is unique and unambiguous.
  • weak_ptr used to break loops in trees of shared_ptr. They are not detected automatically.
  • vector. Don't forget this one! Use it to create dynamic arrays of anything.

PS: You forgot to ask about destructors. IMO, destructors are what gives C++ its personality, so be sure to use a lot of them!

like image 184
rodrigo Avatar answered Oct 09 '22 01:10

rodrigo


This is a fairly broad question, but I'll give you a starting point.

What's known in C as a "stack variable" is also called an object with "automatic storage". The lifetime of an object with automatic storage is fairly easy to understand: it's created when control reaches the point it's defined, and then destroyed when it goes out of scope:

int main() {   int foo = 5; // creation of automatic storage   do_stuff();   foo = 1;    // end of function; foo is destroyed. } 

Now, a thing to note is that = 5 is considered part of the initialization syntax, while = 1 is considered an assignment operation. I don't want you to get confused by = being used for two different things in the language's grammar.

Anyway, C++ takes automatic storage a bit further and allows arbitrary code to be run during the creation and destruction of that object: the constructors and destructors. This gives rise to the wonderful idiom called RAII, which you should use whenever possible. With RAII, resource management becomes automatic.

what are all these things like shared_ptr, weak_ptr, etc.?

Good examples of RAII. They allow you to treat a dynamic resource (malloc/free calls) as an automatic storage object!

Most importantly, when is it correct to copy/assign/whatever = is in C++, and when do you want to use pointers? In C, I got very used to throwing pointers around a lot, because pointer assignment is cheap but struct copying is less so. How do C++'s copy semantics affect this?

const references everywhere, especially for function parameters. const refs avoid copies and prevent modification of the object. If you can't use const ref, chances are a normal reference is suitable. If for some reason you want to reset the reference or set it to null, use a pointer.

What are all the ways to create a C++ object? Direct/copy constructor, assignment, etc. How do they work?

In short, all constructors create objects. Assignment doesn't. Read a book for this.

like image 41
Pubby Avatar answered Oct 08 '22 23:10

Pubby