neural.atlant
neural.atlant

Reputation: 225

Reference initialization as member of class

I have class "Segment":

class Segment
{
private:
    Point &_a;
    Point &_b;
public:
    Segment(const Point& start, const Point& end);
    ~Segment(); 
};

This is realization of constructor:

Segment::Segment(const Point& start, const Point& end): 
    _a(Point(start.x(), start.y())), 
    _b(Point(end.x(), end.y())), 
    _segmentID(_freeID++)
    {
        return;
    }

It complile with warnings:

warning C4413: reference member is initialized to a temporary that doesn't persist after the constructor exits

How to initialize references in class constructor correctly? How to get rid of this warning?

P.S. Here is another constructor with the same problem:

Segment::Segment(double x1, double y1, double x2, double y2): 
    _a(Point(x1, y1)), 
    _b(Point(x2, y2)),
    _segmentID(_freeID++)
    {
        return;
    }

Upvotes: 0

Views: 154

Answers (2)

Freddy
Freddy

Reputation: 2279

Your problem is this.

Segment::Segment(const Point& start, const Point& end): 
    _a(Point(start.x(), start.y())), 
    _b(Point(end.x(), end.y())), 
    _segmentID(_freeID++)
    {
        return;
    }

In your initializer list you are creating a temporary object.

Point(start.x(), start.y())

This temporary object is destroyed once the scope it is created in is exited and is what the error message you're referencing is telling you.

You could change your initializer to the following:

Segment::Segment(Point& start, Point& end): 
    _a(start), 
    _b(end), 
    _segmentID(_freeID++)
    {
    }

The problem with this is that the lifetime of _a and _b are out of your control. If these are stack based variables then they could be destroyed while your object is still relying on them being valid variables.

Also, the return from your constructor is pointless.

Upvotes: 1

tmlen
tmlen

Reputation: 9092

Segment::Segment(const Point& a, const Point& b) :
    _a(a), _b(b), _segmentID(_freeID++) { }

And the Points used to construct the Segment must persist for as long as the Segment since it keeps a reference to it.

Point(start.x(), start.y()) would construct a new (temporary) Point object, but using that to initialize the reference is invalid because the temporary object goes out of scope immediately.

Upvotes: 0

Related Questions