I have a pointer / dereferencing issue where I'm getting the error:
Declaration of reference variable requires an initializer
With the following:
CastInfo& out;
if(SegmentCast(mOwner->GetGame()->GetPlayer(), mLineSegment, out))
{
This SegmentCast function is defined with the following parameters:
bool SegmentCast(Actor* actor, const LineSegment& l, CastInfo& outInfo)
and CastInfo
is defined as:
struct CastInfo
{
// Point of collision
Vector3 mPoint;
// Normal at collision
Vector3 mNormal;
// Owning actor you collided with
class Actor* mActor = nullptr;
};
Because there's no constructor, I can't initialize out by doing CastInfo& out = CastInfo()
, and yet I don't know how else to call that SegmentCast function with the CastInfo output.
How can I properly call this function with this reference variable?
CodePudding user response:
2 issues with this code
CastInfo& out;
if(SegmentCast(mOwner->GetGame()->GetPlayer(), mLineSegment, out))
{
First you actually have to have an instance of CastInfo somewhere that can be referenced in that call to SegmentCast
Second you cannot create a refernce thats not bound to an actual object (unlike a pointer)
If you want a local instance do
CastInfo out;
if(SegmentCast(mOwner->GetGame()->GetPlayer(), mLineSegment, out))
{
This creates a local stack instance, a reference to it will be passed (you dont have to do anything else, the compiler knows thats what the function wants)
Or if you need a heap instance do
CastInfo *out= new CastInfo();
if(SegmentCast(mOwner->GetGame()->GetPlayer(), mLineSegment, *out))
{
This makes a pointer to a heap object. To pass it to the function you need to derference it (*out
) and then the compiler will pass it as a reference (just like the first example)
Ideally you would use std::unique_ptr
rather than a raw new
and pointer. If you do not, then remeber to delete out once you are done
CodePudding user response:
Be wary of analogies between pointers and references; that will usually be confusing. A pointer can point to nowhere; a reference always refers to an object. So, while you can write CastInfo* out;
, which creates a pointer with an unspecified value, you cannot write CastInfo& out;
; it is simply not allowed. If you need to create a reference there must be an object that it refers to:
CastInfo info;
CastInfo& out = info;