const A& a = A() //合法
A& a = A() //非法
It is likely to lead to unexpected behaviour. Imagine something first like this:
std::string & make_upper( std::string & s )
std::transform( s.begin(), s.end(), s.begin(), ::toupper );
Reasonable enough implementation. Now first suppose you tried to pass in char * instead.
char text = "Hello world";
make_upper( char_text );
std::string has an implicit constructor from const char * (and thus char *) so it might create a temporary which can be used for this function, but if that were allowed, the std::string makes a copy so you would only be modifying the copy and the changes would be lost.
In case you think that this should apply only to implicit constructors and not temporaries returned from functions, there are a lot of cases whereby objects are constructed through a helper function because these functions can resolve the template parameters (needed for the class) so you don't need to supply them to the function. (bind1st and make_pair are examples of such functions).
Note that if the class is a wrapper for a non-const reference or pointer, you can work around the situation by using a const reference to the buffer. For example in class to input to a vector.
template< T >
std::vector< T > & m_v;
vec_wrapper_t( std::vector< T > & v ) : m_v ( v )
void input( std::istream & is ) const
// implement input to the vector
template < typename T >
vec_wrapper_t< T > vec_wrapper( std::vector< T > & v )
return vec_wrapper_t< T >( v );
template < typename T >
std::istream & operator>>( std::istream & is, const vec_wrapper_t & vw )
vw.input( is );
1. That you pass in vec_wrapper_t as const reference (or value) even to the overload of operator >> from istream
2. vec_wrapper is a typical function that resolves the template parameter for you and returns a temporary.
3. with the code above, if v is a vector and is is an input stream you can write is >> vec_wrapper( v ) in your code because of the fact that it's a const reference.
4. In reality vec_wrapper_t is going to have other features, (in my case it has the delimiters used for inputting). You can't get operator>> to write these because you vec_wrapper_t is temporary, i.e. anything you wrote to it would be lost and for the next vector you tried to write to, it would not be there.
reply by me：
what do you mean is in c++ there exists plenty of codes which may create temporary objects, if we do not define temporary as const, we will suffer much more buggy codes? With the definition of temporary as const, the compiler can find out these bugs ?