Re: Difference between T a = x and T a(x)
 
On 10 Jun., 16:06, Nobody <Nob...@Nowhere.com> wrote:
I always thought that the two construction
    T a = init;
    T a(init);
were equivalent. A collision with the auto_ptr in Microsoft Visual
Studio 2005 told me that they are different.
What exactly is the difference between these two?
The first one is a copy-initialization. The 2nd one is a direct-
initialization. The only practical difference is that copy-
initialization relies on *implicit* constructors only and doesn't
allow some intermediate conversion involving another type. Direct-
initialization can also make use of explicit constructors and may
involve conversions of parameters:
   class foo {
   public:
     foo(int);
     foo(std::string);
     explicit foo(std::pair<int,int>);
   };
   int bar() {
     foo f1 (23);                    // OK
     foo f2 = 42;                    // OK
     foo f3 ("hello");               // OK
     foo f4 = "hello";               // ill-formed
     foo f5 (std::make_pair(23,42)); // OK
     foo f6 = std::make_pair(23,42); // ill-formed
   }
The initialization of f2 works because the parameter is implicitly and
directly convertible to a foo object. The initialization of f4 is ill-
formed because it would require an intermediate temporary of another
type (std::string). The initialization of f6 is ill-formed because
there is no implicit constructor that takes a pair of ints.
std::auto_ptr has an explicit constructor you can't use via copy-
initialization. This explicit constructor takes a raw pointer as
parameter.
   int baz() {
     auto_ptr<int> ap1 = 0; // ill-formed.
     auto_ptr<int> ap2 (0); // OK
   }
Cheers!
SG
-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]