Re: private copy constructor and reference args
On Aug 12, 12:15 pm, Siddharth Jain <siddharthjain...@gmail.com>
wrote:
On Aug 12, 7:47 am, John Salmon <jsal...@thesalmons.org> wrote:
<snip>
class Foo {
Foo(const Foo& f);
public:
Foo() {}
};
void
func( const Foo& foo){
}
int
main(int argc, char **argv){
#ifndef EXPLICIT_TEMPORARY
func(Foo());
#else
Foo f;
func(f);
#endif
return 0;}
</snip>
Gcc (4.1.1) says:
[jsalmon@river junk]$ gcc noncopyable.cpp
noncopyable.cpp: In function 'int main(int, char**)':
noncopyable.cpp:2: error: 'Foo::Foo(const Foo&)' is private
noncopyable.cpp:14: error: within this context
[jsalmon@river junk]$ gcc -DEXPLICIT_TEMPORARY noncopyable.cpp
[jsalmon@river junk]$ a.out
[jsalmon@river junk]$
TC++PL page no 98 says that:
In case of initializer for a const T& :
1 first, implicit type conversion to T is applied if necessary.
2. then, the resulting value is placed in a temporary variable of type
T; and
3. finally, this temporary variable is used as the value of the
initializer.
(eg in case of : const double& cdr=1;
it is actually
double tmp = double(1);
const double& cdr = tmp;
creating this temporary would require a public copy constructor, that
is why gcc is asking for a copy constructor when explicit temporary is
not used.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-...@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ:http://www.comeaucomputing.com/csc/faq.html ]
You're right to observe that the problem is related to const reference
initialization.
The function call is unnecessary baggage.
Also, it seems that Comeau complains if I turn off C++0x extensions.
But I am still confused. In the following code, how is the
initialization of g
different from the initialization of h, and what changes in C++0x to
make the
initialization of h acceptable?
class Foo {
Foo(const Foo& f);
public:
Foo(){}
};
int
main(int argc, char **argv){
Foo f; // ok, default ctor
const Foo &g(f); // ok
const Foo &h((Foo())); // fails g++, Comeau without C++0x
extensions
return &g!=&h;
}
---
[ 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://www.comeaucomputing.com/csc/faq.html ]