Why can't const T * & bind to T *?

VS2010 shows error C2440: 'return' : cannot convert from 'char *' to 'const char *&in f3below. Why is it impossible to return a char*when return type const char*&?

const char* const& f1()
{
    static char* x = new char[5]();
    return x;
}

char* const& f2()
{
    static char* x = new char[5]();
    return x;
}

const char* & f3()
{
    static char* x = new char[5]();
    return x;    // error C2440
}

char* & f4()
{
    static char* x = new char[5]();
    return x;
}
+5
source share
3 answers

From clause 8.5.3 / 2 of the C ++ 11 standard:

A link cannot be changed to refer to another object after initialization. Please note that link initialization is treated very differently than assignment to it. Passing the argument (5.2.2) and the value of the return function (6.6.3) are initializations .

, . f3() , :

char c = 'a';
char* x = &c;
const char*& y = x; // ERROR!

, y, - const char*, , (.. x), char*. , , , ( , )), .

const const char* , , : char const char*, .

, const char* char* :

"cv1 T1" "cv2 T2" "cv1 T1" "cv2 T2" , T1 - , T2, T1 T2. "cv1 T1" - "cv2 T2" , T1 T2, cv1 cv-, cv-, cv2. [...]

, f2() , , :

char c = 'a';
char* x = &c;
char* const& y = x; // OK

char* const, ( const char*) - char* , * ( const ).

, 8.5.3/5:

"cv1 T1" "cv2 T2" :

- lvalue

  • lvalue ( ), "cv1 T1" - "cv2 T2,"

[...]

. char* const char* , ( f2() ). , const char* char* -, ( f3() ).

+5

char ** const char **.

f3() = "hello";

f3 , x.

+2
#include <iostream>
void problem( const char*& output, const char* input )
{
  output = input; // legal, const char*& = const char*
}

int main() {
  const char buff[] = "hello";
  char* out = nullptr;
  problem( const_cast<const char*&>(out), &buff[0] );
  out[0] = 'H'; // I just changed a const array first character
  std::cout << &buff[0] << "\n";
}

"Hello", , undefined. const_cast. const char*& char*, const_cast undefined.

", ," , OP! "

.

// the "legal" way to do what the OP wants to do, but it leads to undefined
// behavior:
const char*& problem2( char*& c ) { return const_cast<const char*&>(c); }
void problem3( const char*& left, const char* right ) { left = right; }

#include <iostream>
int main() {
  char* c = nullptr;
  char const* buff = "hello undefined behavior";
  problem3( problem2(c), buff );
  c[0] = 'H';
  std::cout << buff << "\n";
}

"Hello undefined ".

"", , " char*& const char*&, char* const char*&.

:

void problem3( const char*& left, const char* right ) { left = right; }
const char*& problem4( char x = 0 ) {
  static char* bob = nullptr;
  if (bob && x)
    bob[0] = x;
  return const_cast<const char*&>(bob);
}
#include <iostream>
int main() {
  char const* buff = "hello problem";
  problem3( problem4(), buff );
  problem4('H');
  std::cout << buff << "\n";
}

, H (, , undefined , H).

+2

All Articles