BUG: 'char *' Passed to 'const char * &' Violates Type SafetyLast reviewed: July 24, 1997Article ID: Q122540 |
The information in this article applies to:
SYMPTOMSVisual C++ incorrectly allows a pointer to be passed to a function that takes a non-const reference to a pointer to a const. This breaks C++ type safety and allows the const data assigned to the reference to be modified by the pointer after the function has returned.
RESOLUTIONTo protect the const data, the reference should be a reference to a const pointer to a const, that is: const char * const &.
STATUSMicrosoft has confirmed this to be a problem in the Microsoft products listed at the beginning of this article. We are researching this problem and will post new information here in the Microsoft Knowledge Base as it becomes available.
MORE INFORMATIONA reference may only be initialized with an lvalue expression of the same type or a class derived from that type. If this is not the case, the reference must be declared const. The following sample includes a non-const reference of type const char*, which is being initialized with an expression of type char*. The compiler should, but does not, generate an error. The program prints this string:
const_ptr = Xhis is a 'const char *' Sample Code
/* Compile options needed: none */ #include <iostream.h> const char * const_ptr = "This is a 'const char *'"; void func ( const char* & reference) { reference = const_ptr; } void main() { // char *non_const_ptr = const_ptr; // Not allowed. char *non_const_ptr; // *const_ptr = 'X'; // Not allowed. func( non_const_ptr ); // // 'const char *' is violated now. // *non_const_ptr = 'X'; // Mess up first letter of string cout << "const_ptr = " << const_ptr << endl; } |
Additional query words: 8.0c 8.00c 9.0 9.00 10.00 10.10 10.20
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |