What if I write return statement in constructor?

前端 未结 2 1170
一个人的身影
一个人的身影 2020-12-07 19:21

What if I write return statement in constructor? Is it standard conformant?

struct A
{ 
     A() { return; } 
};

The above code compiles fi

相关标签:
2条回答
  • 2020-12-07 19:37

    Yes, using return statements in constructors is perfectly standard.

    Constructors are functions that do not return a value. The family of functions that do not return a value consists of: void functions, constructors and destructors. It is stated in 6.6.3/2 in the C++ standard. The very same 6.6.3/2 states that it is illegal to use return with an argument in a function that does not return a value.

    6.6.3 The return statement

    2 A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function.

    Additionally, 12.1/12 states that

    12.1 Constructors

    12 No return type (not even void) shall be specified for a constructor. A return statement in the body of a constructor shall not specify a return value.

    Note, BTW, that in C++ it is legal to use return with an argument in a void function, as long as the argument of return has type void

    void foo() {
      return (void) 0; // Legal in C++ (but not in C)
    }
    

    This is not allowed in constructors though, since constructors are not void functions.

    There's also one relatively obscure restriction relevant to the usage of return with constructors: it is illegal to use return in function-try-block of a constructor (with other functions it is OK)

    15.3 Handling an exception

    15 If a return statement appears in a handler of the function-try-block of a constructor, the program is ill formed.

    0 讨论(0)
  • 2020-12-07 19:50

    Perhaps the notion of having typeless return in constructors is to control the termination of constructor function.

    struct A
    { 
    // more definitions     
    A() 
    { 
    if( !goodToGoOn)  
     return;
    // the rest of the stuffs go here
    } 
    };
    
    0 讨论(0)
提交回复
热议问题