开发者

Casting an object to a reference?

开发者 https://www.devze.com 2023-03-03 11:38 出处:网络
I\'ve been reading some OSS code lately and stumbled upon this peculiar piece: class Foo { ..... }; void bar() {

I've been reading some OSS code lately and stumbled upon this peculiar piece:

class Foo { ..... };
void bar() {
    Foo x;
   Foo *y=new Foo();
   x=(const Foo &) *y;
}

For the life of me I can't find documentation about the behavior of casting an object to a cons开发者_开发百科t reference.


x=(const Foo &) *y; is assignment. The only reason I see to explicitly cast to const reference is to have Foo::operator=(const Foo &) called for assignment if Foo::operator=(Foo &) also exists.


x=(const Foo &) y; line invokes undefined behavior.
Prefer to avoid C-style casts; they are easy to get wrong. You silence the compiler, so they are too dangerous.

Edit: this answer was relevant at the time, when in the question y was not dereferenced prior to the cast to const Foo &. For the answer to the question after *y edit, please see the answer given by n0rd


Interestingly, the misread code could still be possible, if Foo has a non-explicit constructor that takes a Foo* pointer.

#include <iostream>

class Foo{
public:
  Foo() {}
  Foo(Foo*) { std::cout << "Aha!\n"; }
};

int main(){
  Foo* pf = new Foo;
  Foo f = (const Foo&)pf;

  std::cin.get();
}

See the output at Ideone.
Interestingly, if you make the constructor explicit, it shows the undefined behaviour explained by @usta.


You'll have to declare x after y:

Foo* y = new Foo();
Foo& x = *y;

Alternatively:

Foo x;
Foo* y = new Foo();
x = (Foo&)*y;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号