Calling constructors in c++ without new

前端 未结 7 1555
离开以前
离开以前 2020-12-04 05:20

I\'ve often seen that people create objects in C++ using

Thing myThing(\"asdf\");

Instead of this:

Thing myThing = Thing(\"         


        
7条回答
  •  眼角桃花
    2020-12-04 06:02

    Both lines are in fact correct but do subtly different things.

    The first line creates a new object on the stack by calling a constructor of the format Thing(const char*).

    The second one is a bit more complex. It essentially does the following

    1. Create an object of type Thing using the constructor Thing(const char*)
    2. Create an object of type Thing using the constructor Thing(const Thing&)
    3. Call ~Thing() on the object created in step #1

提交回复
热议问题