简体   繁体   English

访问结构中的数组会导致发出叮当声警告

[英]Accessing an array within a struct causes warnings with clang

struct test{
   char c_arr[1];
};

test array[1] = {{1}};

test get(int index){
 return array[index];
}

int main(){
  char* a =  get(0).c_arr;
  return 0;
}

Compiling this with g++ has no warnings but with clang++ prints the following:g++编译它没有警告,但用clang++打印以下内容:

warning: temporary whose address is used as value of local variable 'a' will be destroyed at the end of the full-expression

Is this incorrect?这不正确吗? does get(0).c_arr not return a pointer to a global array? get(0).c_arr不返回指向全局数组的指针吗?

or does get(0) return a temporary variable and the compiler thinks c_arr is just an instance of it, and not global, by mistake?还是get(0)返回一个临时变量并且编译器错误地认为c_arr只是它的一个实例,而不是全局变量?

Edit编辑

Why passing this temp variable to a function works without warnings?为什么将此临时变量传递给函数可以在没有警告的情况下工作?

void call(char* in){}

int main(){
  call(get(0).c_arr);
  return 0;
}

get returns by-value, then get(0) does return a temporary which gets destroyed after the full expression, left a being a dangling pointer. get的价值回报,那么get(0)并返回一个临时的哪个被充分表达后销毁,留下a被悬空指针。

Note that the returned temporary test is copied from array[index] , including the array data member c_arr .请注意,返回的临时test是从array[index]复制的,包括数组数据成员c_arr a is supposed to point to the 1st element of the data member array c_arr of the temporary test , after the full expression (ie the ; in char* a = get(0).c_arr; ) the whole temporary test (and its data member c_arr ) is destroyed, then a becomes dangling. a应该指向临时test的数据成员数组c_arr的第一个元素,在完整表达式之后(即; in char* a = get(0).c_arr; )整个临时test (及其数据成员c_arr ) 被销毁,然后a变成悬空。

If get returns by-reference then it'll be fine.如果get通过引用返回的,那就没问题了。

test& get(int index){
 return array[index];
}

EDIT编辑

The code you added is fine.你添加的代码没问题。 The temporary is destroyed after the full expression, ie after ;临时在完整表达式之后被销毁,即在; in call(get(0).c_arr);call(get(0).c_arr); . . The pointer passed to call remains valid inside call .通过指针call仍然有效的内部call

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM