Re: explicit auto_ptr<T>::auto_ptr(T*) ?
On Mar 15, 11:49 am, Sousuke <s0s...@gmail.com> wrote:
The constructor for auto_ptr<T> which takes a T* is explicit,
which is requiring me to create a temporary when passing a T*
to a function that takes an auto_ptr<T> (by value).
Whether a conversion is implicit or explicit doesn't change
anything with regards to temporaries. Depending on the context,
making a conversion implicit reduces the number of characters
you have to type, and increases the risk of error and the
probability of ambiguity. Generally, the balance weighs against
implicit conversions (but I'm not so sure here).
Something like this:
void f1(auto_ptr<int> p)
{
}
void f2()
{
int* p = new int;
// I have to do either:
f1(static_cast<auto_ptr<int> >(p));
// or:
//f1(auto_ptr<int>(p));
}
And?
In another case, I have an auto_ptr<T>, where T is a subclass
of the T of the auto_ptr parameter of the function I'm
calling:
class A { public: virtual ~A() {} };
class B : public A {};
void f1(auto_ptr<A> p)
{
}
void f2()
{
auto_ptr<B> p(new B);
// I still have to do either:
f1(static_cast<auto_ptr<A> >(p));
// or:
//f1(auto_ptr<A>(p));
}
I would expect that by calling:
f1(p);
the template constructor of auto_ptr<T> which takes an
auto_ptr<Other>& would be called, where Other is the template
parameter and where T* is compatible with Other*.
This is what I would expect too. If I read the standard
correctly, it's also what the standard requires; the converting
constructor:
template<typename Y> auto_ptr(auto_ptr<Y>&) throw();
is not explicit.
However, the compiler says:
error C2664: 'f1' : cannot convert parameter 1 from
'std::auto_ptr<_Ty>' to 'std::auto_ptr<_Ty>'
with
[
_Ty=B
]
and
[
_Ty=A
]
No user-defined-conversion operator available that can perform
this conversion, or the operator cannot be called
It's hard to say. It may be a bug in the compiler, but auto_ptr
has undergone a number of changes in time, and it's possible
that the library simply isn't up to date.
Does auto_ptr have some magic to avoid the creation of a
temporary in either of these cases?
Again: having an implicit conversion doesn't eliminate the
temporary. And making it explicit doesn't create an additional
temporary.
--
James Kanze