Topic: (corr) copy initialization question


Author: "Mike Wahler" <mkwahler@mkwahler.net>
Date: 2000/07/25
Raw View
Mike Wahler <mkwahler@mkwahler.net> wrote in message news:...
> Gil Shafriri <gilsh@microsoft.com> wrote in message
> news:397a0d79@news.microsoft.com...
> > According to what I read in the standard (12.6.1) - the following code
> > should not compiles :
> > class Foo
> > {
> > public:
> > Foo(int){}
> > private:
> > Foo(const Foo&);
> > };
> >
> > void main(int argc, char** argv[])
> > {
> > Foo x = 1;
> > }
> >
> > The compiler has to create temporary by calling Foo(int)
>
> Yes it calls Foo::Foo(int), but it doesnt create a temporary,
> it creates 'x' directly.
>
> >then to copy
> > initialize
> > x using this temporary.
>
> There is only 'x', no temporary, thus no copy occurs.
>
> > This code should not compile because Foo copy ctor
> > is
> > not accessible.
>
> Any code that *calls* the copy constructor won't compile.
> The initialization above doesn't call the copy ctor.
>
> > Even the optimization the compiler can do by calling
> > Foo(int) instead can be
> > applied only if copy ctor is accessible. However - this code compiles OK
> > under vc6.
> > This looks to me as compiler bug - Do I miss something ?
>
> Yes, I think you missed the difference between initialization and
> assignment.
>
> Foo x =1; // initialization, not assignment
>
> will be interpreted by the compiler as:
>
> Foo x(1);  // calls public constructor

i.e. the passed argument is type const int, not
Foo&, which is the type of the copy ctor's argument.
So the copy ctor is *not* called.

>
> However, consider:
>
> Foo x;
> Foo y;
> x = y; // tries to call incaccessible (private) copy-constructor,
>           // so should give compile error.

The above should have been:

Foo x;
Foo y(x); // calls copy constructor

x = y // calls Foo::operator=(Foo &), if defined.
// If operator= is not defined, it does a memberwise
// assignment.

-Mike






---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]