0 introduction
The pointer (Pointer) yes C、C++ as well as Java、Go A very central and important concept of language , And quote (Reference) It's an equally important concept built on pointers .
Pointer is necessary and important for any programming language , although Python The concept of pointer is deliberately blurred and limited , But the pointer is for Python It is still a topic that must be discussed in depth .
This article is based on C++ And Python, it has been reviewed that Python Some behaviors related to pointers and references in .
1 What is a pointer ? Why do I need a pointer ?
The pointer has two meanings :
(1) A pointer type that refers to a data type , Such as the type of shaping pointer 、 Pointer pointer type
(2) It refers to a type of variable with memory address , That is, pointer variable
The two meanings of the pointer are closely related : As a variable , You can get a memory address through a pointer , So you're ready to access the values on this address ; As a type , It determines the correct offset length of the memory address , It should be equal to the unit memory size of the current type .
If a pointer is missing a pointer type , namely void *, Obviously , Although it saves the memory address , But this is just a starting address , The pointer will not know the offset from the starting point back , Thus, the pointer resolving operation is rejected ; And if a pointer is missing an address , namely nullptr, It can't read the memory in a specific location at all .
The main meaning of the existence of the pointer is as follows :
pass-by-pointer The benefits include, but are not limited to :
thus it can be seen , Pointer related operations are necessary or very important for programming .
2 C++ Citation in
stay C++ in , References have properties similar to pointers , But more invisible and strict .C++ There are two kinds of quotations :
2.1 lvalue reference
The lvalue reference is bound to lvalue in its initialization phase , And there is no rebinding .
An lvalue reference has almost the same properties as the bound lvalue , The only difference is decltype Statement :
int numA = 0, &lrefA = numA; // Binding an lvalue
cout << ++lrefA << endl; // Use the lvalue reference as lvalue & rvalue
decltype(lrefA) numB = 1; // Error!
Left quoting is often used in pass-by-reference:
void swap(int &numA, int &numB)
{
int tmpNum = numA;
numA = numB;
numB = tmpNum;
}
int main()
{
int numA = 1, numB = 2;
swap(numA, numB);
cout << numA << endl << numB << endl; // 2 1
}
2.2 Right quoting
The right value reference is bound to the right value at its initialization stage , It is often used for move constructors and move assignment operations . In these occasions , The move constructor and move assignment take over the moved object through the right value reference .
Right value references are independent of the content of this article , So I won't go into details here .
3 Python Citation in
3.1 Python There is no reference
It can be seen from the above discussion that , although “ quote ” about Python Is a very common term , But it's obviously not accurate —— because Python There is no right to left / Binding operation of right value , So there is no left quotation , There is no right value reference .
3.2 Python Pointer operation of
It's not hard to find out , although Python There is no reference , But its variable behavior and pointer behavior have a high degree of similarity , This is mainly reflected in the following aspects :
thus it can be seen ,Python Variables are more like ( Something incomplete ) Pointer to the variable , Instead of quoting variables .
3.2.1 Constructor returns pointer
about Python Description of , There is a very common saying :“ Everything is the object ”.
But in this sentence , There is a very important fact that is often ignored : Object is a value , Not a pointer or reference .
therefore , The exact description of this sentence should be corrected to :“ Everything is ( Something incomplete ) The pointer ”. Although the modified description is abstract , But it's more accurate .
And because objects come from constructors , So far we know :Python The constructor of will construct an anonymous object , And returns a pointer to this object .
This is a Python The first important connection with the pointer .
Describe... In code , about Python Code :
sampleNum = 0
It's not like C++ Code :
int sampleNum = 0;
It's more like :
int __tmpNum = 0, *sampleNum = &__tmpNum;
// perhaps :
shared_ptr<int> sampleNum(new int(0));
3.2.2 __setitems__ Operation will implicitly resolve pointer
Python Another important connection with the pointer is Python Implicit pointer removal behavior of .
although Python There is no explicit pointer operation , but ( Yes and no )__setitems__ Operation will implicitly resolve pointer , To modify a variable by this method is equivalent to modifying the original value of the variable by solving the pointer operation .
This nature means :
about Python Code :
numList = [None] * 10
# Rebinding
numList = [None] * 5
It is equivalent to :
int *numList = new int[10];
// Rebinding
delete[] numList;
numList = new int[5];
delete[] numList;
thus it can be seen , Yes numList Non - __setitems__ operation , Lead to numList Is bound to a new pointer .
because Python Highly dependent on hash table ,“ involve __setitems__ The operation of ” stay Python It's actually a very wide range of behaviors , This mainly includes :
Let's use a slightly more complex example to illustrate this :
For the following Python Code :
class Complex(object):
def __init__(self, real = 0., imag = 0.):
self.real = real
self.imag = imag
def __repr__(self):
return '(%.2f, %.2f)' % (self.real, self.imag)
def main():
complexObj = Complex(1., 2.)
complexObj.real += 1
complexObj.imag += 1
# (2.00, 3.00)
print(complexObj)
if __name__ == '__main__':
main()
It is equivalent to :
class Complex
{
public:
double real, imag;
Complex(double _real = 0., double _imag = 0.): real(_real), imag(_imag) {}
};
ostream &operator<<(ostream &os, const Complex &complexObj)
{
return os << "(" << complexObj.real << ", " << complexObj.imag << ")";
}
int main()
{
Complex *complexObj = new Complex(1., 2.);
complexObj->real++;
complexObj->imag++;
cout << *complexObj << endl;
delete complexObj;
return 0;
}
thus it can be seen , Whether it's int、float This simple Python type , Or our custom class , Its construction behavior is similar to the use of new Construct object and return pointer .
And in Python Any reference to “.” and “[]” The operation of , Are similar to “->” or “*” Pointer operation .
4 Postscript
This paper discusses Python Variables and pointers 、 Quote the relationship between the two concepts , The main argument is “Python There is no reference ” as well as “Python A variable behaves like a defective pointer ” Two arguments .
The above is all the content shared this time , Want to know more python Welcome to official account :Python Programming learning circle , send out “J” Free access to , Daily dry goods sharing
{error_code: 54003, error_msg: