#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's first character
std::cout << &buff[0] << "\n";
}
这会打印“Hello”,这是我刚刚从事未定义行为的证据。为此,我必须使用const_cast
. 如果你可以const char*&
用 a来初始化 a char*
,我就不必这样做const_cast
来调用未定义的行为。
“但是”有人可能会说“这与 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";
}
还打印“你好未定义的行为”。
“但是”,有人可能会说,“你把 achar*&
变成了const char*&
,而不是把 achar*
变成了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
(嗯,实际上,通常是资本的未定义行为H
)。