且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中通过指针和引用传递向量

更新时间:2023-11-08 23:11:04

在功能方面,在您给我们提供的非常有限的上下文中,它们本质上是相同的.

In term of functionality, in the very limited context you gave us, they are essentially the same.

在更一般的视图中,如果要编写通用代码,请考虑将操作和运算符直接绑定到引用,而不绑定到指针

In more general view, if you want to write generic code, consider that operation and operators bind directly to reference, but not to pointers

a = b + c;

编译需要

A operator+(const B&, const C&);

但是

A* operator+(const B*, const C*);

都是不同的野兽.

另外,一个采用引用和采用值的表达式具有相同的语法,但是采用指针的表达式需要引用指针以提供相同的语义,但这导致了不同的表达式语法(*a + *b相对于a+b),因此导致改为少用通用代码".

Also, an expression taking reference and taking value have the same syntax, but an expression taking pointers require pointers to be deference to provide equal semantics, but this leads to different expression syntax ( *a + *b against a+b ) thus leading to "less general code".

相反,如果您正在编写一个具有运行时多态性(并考虑了lyskov替换)的类,则很可能会处理动态分配的对象,因此,通过指针进行操作可能更为自然.

On the counterpart, if you are writing a class that have runtime polymorphism (and lyskov substitution in mind), you will most likely treat dynamically allocated object, and hence, manipulating them through pointers may be more natural.

在两部分相互啮合的灰色区域"中,但是-一般而言,指针获取函数在基于运行时的OOP框架中更为常见,而引用获取函数在基于值的泛型算法"中则更为频繁,其中静态类型可以预料到,并且很可能需要基于堆栈的分配.

There are "grey areas" where the two things mesh, but -in general- pointer taking function are more frequent in runtime based OOP frameworks, while reference taking functions are more frequent in "value based generic algorithms", where static type deduction is expected, and on-stack based allocation is most likely wanted.