对比 C++ 和 Python,谈谈指针与引用
作者 | 樱雨楼
承载通过 malloc、new、allocator 等获取的动态内存
使得 pass-by-pointer 成为可能
避免对实参无意义的值拷贝,大幅提高效率
使得对某个变量的修改能力不局限于变量自身的作用域
使得 swap、移动构造函数、移动赋值运算等操作可以仅针对数据结构内部的指针进行操作,从而避免了对临时对象、移后源等对象的整体内存操作
int numA = 0, &lrefA = numA; // Binding an lvalue
cout << ++lrefA << endl; // Use the lvalue reference as lvalue & rvalue
decltype(lrefA) numB = 1; // Error!
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
}
在任何情况下(包括赋值、实参传递等)均不存在显式值拷贝,当此种情况发生时,只增加了一次引用计数
变量可以进行重绑定(对应于一个不含顶层 const(top-level const)的指针)
在某些情况下(下文将对此问题进行详细讨论),可通过函数实参修改原值
sampleNum = 0
int sampleNum = 0;
int __tmpNum = 0, *sampleNum = &__tmpNum;
// 或者:
shared_ptr<int> sampleNum(new int(0));
numList = [None] * 10
# Rebinding
numList = [None] * 5
int *numList = new int[10];
// Rebinding
delete[] numList;
numList = new int[5];
delete[] numList;
对数组的索引操作
对哈希表的查找操作
涉及__setattr__的操作(由于 Python 将 attribute 存储在哈希表中,所以__setattr__操作最终将是某种__setitems__操作)
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()
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;
}
【END】
热 文 推 荐
☞
☞
☞
点击阅读原文,输入关键词,即可搜索您想要的 CSDN 文章。
你点的每个“在看”,我都认真当成了喜欢