TSL*_*SL_ 2 c++ opencv argument-passing
我已经有一段时间来回这个问题,特别是因为我开始使用OpenCV库.事实是,在OpenCV中,使用了几种方法:
当然,对应于每种方法,调用者格式和功能实现应该是不同的.
所有这些衍生物有什么意义?特别是最后一个(我还没有理解它的用法)
暂时忽略(const),并使用int为清晰起见:
按值传递会在函数体中复制
void funcA(int arg) {
// arg here is a copy
// anything I do to arg has no effect on caller side.
arg++; // only has effect locally
}
Run Code Online (Sandbox Code Playgroud)
请注意,它在语义上进行复制,但允许编译器在某些条件下删除副本.查找副本省略
通过引用传递.我可以修改调用者传递的参数.
void funcA(int& arg) {
// arg here is a reference
// anything I do to arg is seen on caller side.
arg++;
}
Run Code Online (Sandbox Code Playgroud)
按值传递指针.我得到了指针的副本,但它指向调用者参数指向的同一个对象
void funcA(int* arg) {
// changes to arg do not affect caller's argument
// BUT I can change the object pointed to
(*arg)++; // pointer unchanged, pointee changed. Caller sees it.
}
Run Code Online (Sandbox Code Playgroud)
传递对指针的引用.我可以更改指针本身,调用者将看到更改.
void funcA(int*& arg) {
// changes to arg affect caller's argument
// AND I can change the object pointed to.
(*arg)++; // pointee changed
arg++; // pointer changed. Caller sees it.
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,除了它们处理指针之外,后两个与前两个相同.如果你理解指针的作用,那么概念上没有区别.
关于const,它指定是否可以修改参数,或者,如果参数是引用或指针,是否可以修改它们指向/引用的参数.这里的定位const很重要.例如,请参阅const正确性.