i've read in multiple sources c++ reference no more pointer compile time restrictions.
if true, how come forced dereference pointer in order pass function expects parameter?
void fooref(const int&); void foopointer(const int*); int main() { int* p = new int(5); foopointer(p); fooref(*p); // why have dereference pointer? ... }
as understand it, if pass int
fooref
compiler create pointer (reference) address of variable me, if type pointer dereferencing seems pointless. seems me dereferencing pointer, let compiler create pointer dereferenced value seems senseless me.
wouldn't simpler / more performant copy pointer instead of referencing+derferencing value? (perhaps what's happening?)
am missing here? , calling fooref
in such scenario slower calling foopointer
?
, references , pointers produce same code during compilation?
the fact references can implemented in terms of pointers under hood irrelevant. many programming concepts can implemented in terms of other things. may ask why have while
loops when while
can implemented in terms of goto
or jmp
. point of different language concepts make things easier programmer, , references language-concept designed convenience of programmer.
you misunderstanding purpose of references. references give positive side of pointers (cheap pass around), since have same semantics regular values, remove lot of dangers come using pointers: (pointer arithmetic, dangling pointers, etc.) more importantly, reference totally different type pointer in c++ type-system, , madness allow 2 interchangeable (that defeat purpose of references.)
reference syntax designed on purpose mirror syntax of regular value semantics - while @ same time providing ability cheaply pass around memory addresses instead of copying entire values.
now, turning example:
fooref(*p); // why have dereference pointer?
you have dereference pointer here because fooref
takes reference int
, not reference int*
. note can have reference pointer:
void foopointerref(const int*&);
a function takes reference pointer enables modify memory address of pointer within function. in example, have explicitly dereference pointer mirror value semantics. otherwise, looking @ function call fooref(p)
going think fooref
either takes pointer-by-value or pointer-by-reference - not (non-pointer) value or reference.
Comments
Post a Comment