1. ホーム
  2. C++

const char* から char* へ、const 属性の削除

2022-02-28 04:05:36
const char* = char*  

char* to const char* can be converted. Sending it over does not work

The method to remove the const attribute is as follows.

string str = "aaa";
char* p =const_cast<char*>(str.c_str());
printf("%s",p);

const_cast is used to discard the const declaration of a variable, but cannot change the const attribute of the object to which the variable refers. That is, const_cast is used for an object that is not originally const; if it is used for an object that is originally const, the result is unpredictable (the C++ language does not provide for such a case), so please note that I underlined "variable" vs. Please note that I underlined "variable" vs "object" above.
In general const_cast is used in this case: a const pointer (variable) points to a non-const object, and when the programmer confirms this (that the object pointed to is non-const), he uses the const_cast operator to discard the const modifier of the variable to get a non-const pointer, see "The C++ Programming language (special edition)" for details. language (special edition), Section 15.4.2.1.


char* to const char* can be converted. Sending it over does not work


The method to remove the const attribute is as follows.

string str = "aaa";
char* p =const_cast<char*>(str.c_str());
printf("%s",p);


const_cast is used to discard the const declaration of a variable, but cannot change the const attribute of the object to which the variable refers. That is, const_cast is used for an object that is not originally const; if it is used for an object that is originally const, the result is unpredictable (the C++ language does not provide for such a case), so please note that I underlined "variable" vs. Please note that I underlined "variable" vs "object" above.
In general const_cast is used in this case: a const pointer (variable) points to a non-const object, and when the programmer confirms this (that the object pointed to is non-const), he uses the const_cast operator to discard the const modifier of the variable to get a non-const pointer, see "The C++ Programming language (special edition)" for details. language (special edition), Section 15.4.2.1.