Calling constructors in c++ without new

前端 未结 7 1561
离开以前
离开以前 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:05

    In append to JaredPar answer

    1-usual ctor, 2nd-function-like-ctor with temporary object.

    Compile this source somewhere here http://melpon.org/wandbox/ with different compilers

    // turn off rvo for clang, gcc with '-fno-elide-constructors'
    
    #include 
    class Thing {
    public:
        Thing(const char*){puts(__FUNCTION__ );}
        Thing(const Thing&){puts(__FUNCTION__ );}   
        ~Thing(){puts(__FUNCTION__);}
    };
    int main(int /*argc*/, const char** /*argv*/) {
        Thing myThing = Thing("asdf");
    }
    

    And you will see the result.

    From ISO/IEC 14882 2003-10-15

    8.5, part 12

    Your 1st,2nd construction are called direct-initialization

    12.1, part 13

    A functional notation type conversion (5.2.3) can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ... An object created in this way is unnamed. [Note: 12.2 describes the lifetime of temporary objects. ] [Note: explicit constructor calls do not yield lvalues, see 3.10. ]


    Where to read about RVO:

    12 Special member functions / 12.8 Copying class objects/ Part 15

    When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.

    Turn off it with compiler flag from comment to view such copy-behavior)

提交回复
热议问题