warning: return discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
时间: 2023-11-24 22:08:05 浏览: 114
这个 warning 通常出现在你试图从一个返回 const 指针的函数中返回一个非 const 指针的时候。例如:
```c++
const int* foo() {
const int x = 42;
return &x;
}
int* bar() {
return foo(); // warning: return discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
}
```
在这个例子中,`foo()` 函数返回一个指向常量整数的指针,而 `bar()` 函数试图从 `foo()` 函数中返回一个非常量指针,这是不安全的。因为从一个指向常量的指针转换为一个指向非常量的指针可能会导致未定义行为。
解决这个 warning 的方法是要么将 `bar()` 函数的返回类型改为 `const int*`,要么将 `foo()` 函数返回类型改为 `int*`。具体取决于你的需求。
相关问题
initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
这个问题通常发生在尝试修改 const 限定的指针所指向的变量的值时。编译器会提示 initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 的警告信息,告诉你修改 const 限定的指针所指向的变量的值是不安全的。
例如,下面的代码会触发这个警告信息:
```c
const int x = 10;
const int* ptr = &x;
*ptr = 20; // 这里会触发警告信息
```
在这个例子中,变量 x 被声明为 const int 类型,指针 ptr 也被声明为 const int* 类型,表示 ptr 所指向的变量是只读的。然而,在尝试修改 *ptr 的值时,编译器会提示上述警告信息,告诉你这样的操作是不安全的。
warning: initialization discards ‘const’ qualifier from pointer target type
这个warning表示在初始化时,舍弃了指针目标类型的const限定符。这通常发生在声明了一个指向const类型的指针,然后在初始化时将它赋值给了一个指向非const类型的指针,会导致const属性被丢弃。例如:
```
const char *str = "hello";
char *str2 = str; // 报warning:discards ‘const’ qualifier
```
解决这个问题的方法是,在声明指针变量时加上const限定符,或者使用强制类型转换。例如:
```
const char *str = "hello";
const char *str2 = str; // 正确,保留了const属性
char *str3 = (char*)str; // 正确,使用强制类型转换
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsm](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)