c++ passing by const pointer or reference to const pointer

情到浓时终转凉″ 提交于 2019-12-14 03:49:34

问题


I am learning c++, recently i read a book which gives a suggestion that you should use reference to const when possible (if base object will not be changed).

I have a question that should you pass reference to const pointer instead of const pointer, when possible, as reference prevents copied. If not when should i use reference to const pointer.

e.g:

Node(..., Node *const next = nullptr);

OR

Node(..., Node* const& next = nullptr);

回答1:


Passing by const reference is good practice when passing by value (that causes copying of parameters) is a heavy operation.

For example when you are passing a class with some properties to a function it's better to pass it by const reference, In other hand if your are passing types like int or just a pointer it's better not to use references because then you loos performance due to de-reference process.




回答2:


Since references essentially are pointers there is no performance gain in passing pointers by reference.




回答3:


You would only ever use a reference to a pointer if your intention was to modify the pointer value. For example:

ErrorCode MakeSomeObjectForMe(Object *&ptr) {
    if (badPreCondition) {
        return SomeSpecificError;
    }
    ptr = new Object();
    return Succuess;
} 

// Use ptr outside the function.

Otherwise it is not a good idea because it may cost you in performance through double indirection. So you will likely never pass a const & to a pointer.




回答4:


As one example, in concurrent programming passing a ref to const ptr to worker thread may be used as a communication means; the ptr might be actually not const.

mutex sync;
void task(int*const&);
int main(){
    int *paramptr=nullptr;
    thread woker{task,paramptr};
    sync.lock();
    paramptr=whatever;
    sync.unlock();
    worker.join();
    return 0;
}


来源:https://stackoverflow.com/questions/49788157/c-passing-by-const-pointer-or-reference-to-const-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!