c++ - extern const default constructed object -


here code

#include <iostream> using namespace std;  class q { public:     q() { cout << "constructor" << endl; } };  extern const q t/*()*/; //a const q s/*()*/; //b  int main() {     const q t/*()*/; } 

i expect line marked "a" mean creating object t of type q linkage external, , fields can't modified. creation done constructor no arguments, have provided.

in main, expect local t object of type q created in same way, though linkage file, , in fact, scope , duration main.

c++ allows me put or not put parenthesis in const q t/()/; in main. in global scope, in line can put or not put parentheses, , constructor not called either way.

in line b, allowed not put parenthesis since otherwise, compiler confused if defining function prototype.

my questions are:

  1. why allowed flexibility put () or not in line //a, considering in line //b flexibility not exist?

  2. regardless of choice in 1., find "constructor" not printed line a, though printed in line b. why? don't have expectation on this. on 1 hand, reasonable print since see in main c++ understands call 0-argument constructor without parentheses. on other hand, if case, how ever non-defining declaration of class type?

an object declaration extern keyword not definition, unless includes explicit initializer. attempt use () in order force definition step in right direction. however, fails because such declaration () produces syntactic ambiguity, resolved in favor of function declaration, not object declaration.

this applies equally of declarations, not b, seem believe. why claim "this flexibility not exist" line b not clear me: can include () in line b or omit it. in either case declaration valid, except () declare function. (i.e. not mere "flexibility", rather drastic qualitative change.)

for line b problem non-existent, since line b not use extern keyword. without extern line b object definition regardless of whether use explicit initializer or not. , in case leaving (without ()) still triggers default construction, wanted it. same applies local declaration inside main.

line a, on other hand, problematic since in order force definition need explicit initializer, () not want to.

in order work around problem in "classic" c++98 forced use

extern const q t = q(); 

syntax make sure creating object definition initialized default constructor. (pedantically, default construction followed copy construction, that's had live in c++98).

in modern c++ (c++11 , later) can make definition (with default construction) using {} initializer

extern const q t{}; 

or

extern const q t = {}; 

the {}-based syntax obvious reasons not produce ambiguities function declarations.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -