What is implicit dereference in C++

我的梦境 提交于 2019-12-21 22:46:53

问题


What exactly does implicit dereference in C++ mean? Does it mean when I pass a reference to variable into a function parameter I don't need the & in front of it to use its value?


回答1:


I assume that you teaching was trying to explain the difference between pointers and references.

It is relatively common (though not technically accurate) to refer to references as fancy pointers that do implicit de-referencing.

int   x    = 5;
int*  xP   = &x;
int&  xR   = x;


xR  = 6; // If you think of a reference as a fancy pointer
         // then here there is an implicit de-reference of the pointer to get a value.

*xP = 7; // Pointers need an explicit de-reference.

The correct way to think about is not to use the "A reference is a fancy pointer". You need to think about references in their own terms. They are basically another name for an existing variable (AKA an alias).

So when you pass a variable by reference to a function. This means the function is using the variable you passed via its alias. The function has another name for an existing variable. When the function modifies the variable it modifies the original because the reference is the original variable (just another name for it).

So to answer you question:

I don't need the & in front of it to use its value?

No you don't need to add the &.

int f(int& x)  // pass a value by reference
{
    x =5;
}

int plop = 8;
f(plop);
// plop is now 5.



回答2:


Another context in which C++ will implicitly dereference pointers is with function pointers:

void foo() { printf("foo\n"); }

void bar() {
  void (*pf)() = &foo;
  (*pf)(); // Explicit dereference.
  pf(); // Implicit dereference.
}


来源:https://stackoverflow.com/questions/6639057/what-is-implicit-dereference-in-c

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