K
kjm424
I'm wondering if someone can shed some light on a decision made in the
C++ standard.
It would seem that when passing a temporary into a function that takes
a const reference, the copy constructor must be accessible, even though
the copy can be eliminated.
Could somebody tell me the reason for this? Section 8.5.3 of the final
draft explains the requirement (I think), but with no explanation as to
why.
I have included some example source in case my explanation is lacking.
Thanks for any help.
#include <iostream>
class A
{
public:
A(int i) : m_val(i)
{ }
int val() const
{
return m_val;
}
private:
A(const A&);
A& operator=(const A&);
int m_val;
};
void output(const A& a)
{
std::cerr << "Value: " << a.val() << '\n';
}
int main()
{
A a(3);
output(a); // Works
output(A(5)); // Fails to compile - copy constructor not
accesible
return 0;
}
C++ standard.
It would seem that when passing a temporary into a function that takes
a const reference, the copy constructor must be accessible, even though
the copy can be eliminated.
Could somebody tell me the reason for this? Section 8.5.3 of the final
draft explains the requirement (I think), but with no explanation as to
why.
I have included some example source in case my explanation is lacking.
Thanks for any help.
#include <iostream>
class A
{
public:
A(int i) : m_val(i)
{ }
int val() const
{
return m_val;
}
private:
A(const A&);
A& operator=(const A&);
int m_val;
};
void output(const A& a)
{
std::cerr << "Value: " << a.val() << '\n';
}
int main()
{
A a(3);
output(a); // Works
output(A(5)); // Fails to compile - copy constructor not
accesible
return 0;
}