What is the lifecycle of a C++ object?

前端 未结 3 1320
情歌与酒
情歌与酒 2021-02-01 15:24

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

相关标签:
3条回答
  • 2021-02-01 15:52

    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!

    0 讨论(0)
  • 2021-02-01 15:59
    1. There are many ways of implicit object creating in C++ apart from explicit ones. Almost all of them use copy-constructor of the object's class. Remember: Implicit copying may require the copy constructor and/or assignment operator of a T type to be declared in public scope depending on where copying occurs.
      So in course:

      a) explicit creation of a brand new object in stack:

      T object(arg);

    b) explicit copying of an existing object:

    T original(arg);
    ...
    T copy(original);
    

    If T class has no copy constructor defined default implementation is created by compiler. It attempts to create an exact copy of the passed object. This is not always what programmer want, so custom implementation may be useful sometimes.
    c) explicit creation of a brand new object in heap:

    T *ptr = new T(arg);
    

    d) implicit creation of a brand new object which constructor takes only one parameter and has no explicit modifier, for instance:

    class T
    {
    public:
        T(int x) : i(x) {}
    private:
        int i;
    }
    ...
    T object = 5; // actually implicit invocation of constructor occurs here
    

    e) implicit copying of an object passed to a function by value:

    void func(T input)
    {
        // here `input` is a copy of an object actually passed
    }
    ...
    
    int main()
    {
        T object(arg);
        func(object); // copy constructor of T class is invoked before the `func` is called
    }
    

    f) implicit copying of an exception object handling by value:

    void function()
    {
        ...
        throw T(arg); // suppose that exception is always raised in the `function`
        ...
    }
    ...
    int main()
    {
        ...
        try {
            function();
        } catch (T exception) { // copy constructor of T class is invoked here
            // handling `exception`
        }
        ...
    }
    

    g) Creation of a new object using assignment operator. I haven't used word 'copy' because in this case an assignment operator implementation of a particular type matters. If this operator is not implemented default implementation is created by compiler, btw it has the same behavior as default copy constructor.

    class T
    {
        T(int x) : i(x) {}
        T operator=() const
        {
            return T(*this); // in this implementation we explicitly call default copy constructor
        }
    }
    ...
    int main()
    {
       ...
       T first(5);
       T second = first; // assingment operator is invoked
       ...
    }
    

    Well, that's what I am able to remember without looking into Stroustrup's book. May be something is missed.
    While I was writing this, some answer was accepted so I stop at this point. May the details I listed will be useful.

    0 讨论(0)
  • 2021-02-01 16:05

    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.

    0 讨论(0)
提交回复
热议问题