Calling constructors in c++ without new

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

    The compiler may well optimize the second form into the first form, but it doesn't have to.

    #include 
    
    class A
    {
        public:
            A() { std::cerr << "Empty constructor" << std::endl; }
            A(const A&) { std::cerr << "Copy constructor" << std::endl; }
            A(const char* str) { std::cerr << "char constructor: " << str << std::endl; }
            ~A() { std::cerr << "destructor" << std::endl; }
    };
    
    void direct()
    {
        std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
        A a(__FUNCTION__);
        static_cast(a); // avoid warnings about unused variables
    }
    
    void assignment()
    {
        std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
        A a = A(__FUNCTION__);
        static_cast(a); // avoid warnings about unused variables
    }
    
    void prove_copy_constructor_is_called()
    {
        std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
        A a(__FUNCTION__);
        A b = a;
        static_cast(b); // avoid warnings about unused variables
    }
    
    int main()
    {
        direct();
        assignment();
        prove_copy_constructor_is_called();
        return 0;
    }
    

    Output from gcc 4.4:

    TEST: direct
    char constructor: direct
    destructor
    
    TEST: assignment
    char constructor: assignment
    destructor
    
    TEST: prove_copy_constructor_is_called
    char constructor: prove_copy_constructor_is_called
    Copy constructor
    destructor
    destructor
    

提交回复
热议问题