Suppose the class Coord3D
has a method
Point2D& Coord3D::get2DPart(){
return *(Point2D*)this;
}
(Coord3D is just int x; int y; int z;, and Point2D is the 2D version of it with exactly int x; and int y;)
Would the following be safe:
Point2D x = Coord3D(1,2,3).get2DPart();
Or even something like
Coord3D x = Coord3D(1,2,3).getSelf();
where getSelf()
is a function which does return *this;
Seems like it'll probably be safe, but people I asked a开发者_开发知识库ren't sure about it. Is this OK?
Edit: this is what coord3D and Point2D are:
struct Coord3D{
float x; float y; float z;
};
struct Point2D{
float x; float y;
};
Point2D x = Coord3D(1,2,3).get2DPart();
is equivalent to:
Point2D x( Coord3D(1,2,3).get2DPart() );
The temporary Coord3D
you create here will last as long as Point2D
's constructor is being executed. Therefore, using Coord3D
'a this
in that scope is safe.
Note that *(Point2D*)this
smells. If Point3D
inherits from Point2D
, you can just return *this
. If they are unrelated, it's dangerous.
Edit, following the question's update regarding the types:
Given Point2D and Point3D are not related, casting one into the other might work, but it's highly unadvised. A better approach would be to have Point3D inherit from Point2D. Another option would be to add, say, a GetPoint2D()
to Point3D
, and have it create a new 2D point out of the 3D. However, you might have then a real issue with returning references to local variables. Lastly, if you do take the risk and cast as is, at least use reinterpret_cast
and not the C-style cast.
Assuming the cast is valid in the first place (common subsequence of a standard layout type or whatever applies in your case), then yes this is valid as *this
will live until ;
.
精彩评论