Is it safe to keep the reference but not assign the data to the actual variable?

PHPz
Release: 2024-02-08 21:42:09
forward
883 people have browsed it

Is it safe to keep the reference but not assign the data to the actual variable?

php Editor Banana When discussing whether it is safe to keep references but not assign data to actual variables, we need to understand how references and variable assignment work. In PHP, a reference is an alias that points to the memory address of a variable that shares the same memory space. When we keep a reference but don't assign the data to an actual variable, we are actually creating a reference to a space rather than concrete data. This approach is safe in some situations, but there are some caveats.

Question content

I want to keep a list of references in a slice, but I can't find any online resources that explain if it is safe to keep a reference without assigning to a variable?

I mean, is it possible for the operating system to write something into the referenced address that the programmer didn't expect?

Here is a sample code:

type ListItem [8]uint64

list := make([]*ListItem, 0)

list = append(list, &ListChunk{})
list = append(list, &ListChunk{})
list = append(list, &ListChunk{})
Copy after login

In other words, is it guaranteed that the items in a slice named list will remain the same while the program is running, no matter how long it takes?

Workaround

In your case it probably won't (the reference will remain unchanged), but it also depends on what your program does with it:

The Go runtime will not change the references (pointers) stored in the slice during the lifetime of the program, but there is one condition: -You do not reallocate the slice or its element pointers (array of [8]uint64) in the function. As long as you don't reassign a new value to the slice's elements, the reference will remain unchanged.

The above is the detailed content of Is it safe to keep the reference but not assign the data to the actual variable?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!