Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

constant references with typedef and templates in c++

I heard the temporary objects can only be assigned to constant references.

But this code gives error

#include <iostream.h>    
template<class t>
t const& check(){
  return t(); //return a temporary object
}    
int main(int argc, char** argv){

const int &resCheck = check<int>(); /* fine */
typedef int& ref;
const ref error = check<int>(); / *error */
return 0;
}

The error that is get is invalid initialization of reference of type 'int&' from expression of type 'const int'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This:

typedef int& ref;
const ref error;

Doesn't do what you think it does. Consider instead:

typedef int* pointer;
typedef const pointer const_pointer;

The type of const_pointer is int* const, not const int *. That is, when you say const T you're saying "make a type where T is immutable"; so in the previous example, the pointer (not the pointee) is made immutable.

References cannot be made const or volatile. This:

int& const x;

is meaningless, so adding cv-qualifiers to references has no effect.

Therefore, error has the type int&. You cannot assign a const int& to it.


There are other problems in your code. For example, this is certainly wrong:

template<class t>
t const& check()
{
    return t(); //return a temporary object
}

What you're doing here is returning a reference to a temporary object which ends its lifetime when the function returns. That is, you get undefined behavior if you use it because there is no object at the referand. This is no better than:

template<class t>
t const& check()
{
    T x = T();
    return x; // return a local...bang you're dead
}    

A better test would be:

template<class T>
T check()
{
    return T();
}

The return value of the function is a temporary, so you can still test that you can indeed bind temporaries to constant references.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...