英文:
What happens at the compiler level when I dereference a pointer to pass it by reference?
问题
I'm interested in what the compiler does when I dereference a pointer explicitly to pass it by reference:
void foo(A& arg)
{
arg.member = 7;
}
void goo()
{
A* ob = new A();
foo(*ob);
printf(ob->member); // should show 7
}
The reason I'm interested is because I believe bringing the dereference out of the function call would create very different behavior:
void foo(A& arg)
{
arg.member = 7;
}
void goo()
{
A* ob = new A();
A ob_dereferenced = *ob;
foo(ob_dereferenced);
printf(ob->member); // should show whatever A initializes member to
}
英文:
I'm interested in what the compiler does when I dereference a pointer explicitly to pass it by reference:
void foo(A& arg)
{
arg.member = 7;
}
void goo()
{
A* ob = new A();
foo(*ob);
printf(ob->member); // should show 7
}
The reason I'm interested is because I believe bringing the dereference out of the function call would create very different behavour:
void foo(A& arg)
{
arg.member = 7;
}
void goo()
{
A* ob = new A();
A ob_dereferenced = *ob;
foo(ob_dereferenced);
printf(ob->member); // should show whatever A initialises member to
}
答案1
得分: 1
你的比较并不公平,因为在第二个版本中:
void goo()
{
A* ob = new A();
A ob_dereferenced = *ob; // <---- here !!!
foo(ob->member); // should show whatever A initialises member to
}
你正在复制 A
实例。根据 A
是什么,创建第二个实例可能会产生可观察到的副作用。
然而,让我们暂时不考虑这种可观察到的副作用,并使用
struct A { int member = 0; };
那么这两种方式之间没有可观察到的差异:
void moo(A* a) {
foo(*a);
}
和使用本地引用:
void moo(A* a) {
A& b = *a;
foo(b);
}
这两个 moo
的作用是相同的。在启用优化时,不应该期望编译器产生不同的输出。
PS:你两个版本都存在内存泄漏问题。如果你只是需要一个指针作为示例,你不需要使用 new
。例如,A a; A* aptr = &a;
完全可以用作指向 A
的合法指针,你不需要担心内存泄漏问题。上面我避免了这个问题,只是假设指针来自某个地方。
英文:
Your comparison is not a fair one because here in the second version:
> void goo()
> {
> A* ob = new A();
> A ob_dereferenced = *ob; // <---- here !!!
> foo(ob_dereferenced);
> printf(ob->member); // should show whatever A initialises member to
> }
You are making a copy of the A
instance. Depending on what A
is, creating a second instance can have observable side effects.
However, lets put such observable side effects aside, and use
struct A { int member = 0; };
then there is no observable difference between:
void moo(A* a) {
foo(*a);
}
and using a local reference:
void moo(A* a) {
A& b = *a;
foo(b);
}
Those two moo
do the same. There is no reason to expect different output from the compiler when optimizations are turned on.
PS: Your both versions leak memory. If you need a pointer for an example you do not need new
. For example A a; A* aptr = &a;
makes up for a totally fine pointer to A
and you dont need to worry about leaks. Above I avoided the issue, by simply assuming the pointer comes from somewhere.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论