home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 31,977 of 33,346   
   Ulrich Eckhardt to All   
   Re: What is the purpose of the explicit    
   02 Mar 12 13:03:25   
   
   From: doomster@knuut.de   
      
   Krzysztof Żelechowski wrote:   
   > Foo a = 42;   
   >   
   > Compile-time error: can't convert 42 to an object of type Foo   
   >   
   > What is implicit about that definition?   
      
   "42" is an int, "a" is a Foo. This implicitly converts the int to a foo.   
   In this case, it's not really obvious, but imagine a function taking a   
   Foo. If you try to call the function with 42, that must first be converted   
   to a Foo, and the "explicit" keyword disables an implicit conversion.   
      
   When is this needed? Imagine a smart pointer type like std::auto_ptr who's   
   ctor isn't explicit. If you write a function taking such a pointer, and   
   you pass a raw pointer to some object to it, the raw pointer is used to   
   initialize the smart pointer, the function is called, the function returns   
   and the temporary smart pointer instance is destroyed, deleting the object   
   it points to! So, your pointer, which previously pointed to a valid object   
   has suddenly turned into a dangling pointer!   
      
   When to apply explicit? In general, I'd apply it to any constructor taking   
   a single argument (with the exception of the copy constructor) unless it   
   is safe without the explicit and I have a reason to want the implicit   
   conversion. Examples when this is save is e.g. the initialization of a   
   string with a character literal, the character string is copied to the   
   internal buffer but remains intact. However, note that you could argue   
   that this is wrong, because copying is an expensive operation. There were   
   cases where I added an "explicit" to some code and found a few cases that   
   stopped compiling. These cases were surprising, because the copying there   
   was expensive and unnecessary, and instead of making the explicit   
   initialization to make it compile as-is, I rewrote it a bit to avoid the   
   copying altogether.   
      
   HTH   
      
   Uli   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca