Avoid constructing temporary object when doing Member Initialize list for Aggregation in a class

  aggregation, c++, class, move-semantics

I’m trying to initilize the Line2D object using two other object Point2D (A line consists of 2 points) using member initialization list.
In both Point2D and Line2D classes I have the toString() just to show which class is being created/destroyed.

This is my main:

int main() {
    Line2D l1{ {-1, 9}, {9.0, 10} };

    cout << endl << endl;

    return 0;
}

After it was running, here’s the result:

(-1 , 9) cons
(9 , 10) cons
Your 2D Line: (-1 , 9) -> (9 , 10) cons
(9 , 10) destroy
(-1 , 9) destroy

Your 2D Line: (-1 , 9) -> (9 , 10) destroy
(9 , 10) destroy
(-1 , 9) destroy

It works fine, however there are two temporary Point2D objects are copied into the Line:

(-1 , 9) cons
(9 , 10) cons
Your 2D Line: (-1 , 9) -> (9 , 10) cons
(9 , 10) destroy
(-1 , 9) destroy

And I want the temporary object to be moved into Line2D construtor.

How do I do that? Is it something with C++11 Move Semantics??

Here are my classes:

#include <sstream>
using std::cout;
using std::endl;

class Point2D
{
private:
    float _xCoordinate = 0;
    float _yCoordinate = 0;

public:

    Point2D() {
        cout << this->toString() << " cons" << endl;
    }
    explicit Point2D(float x) : _xCoordinate(x) {
        cout << this->toString() << " cons" << endl;
    }
    Point2D(float x, float y) : _xCoordinate(x), _yCoordinate(y) {
        cout << this->toString() << " cons" << endl;
    }

    std::string toString() {
        std::stringstream writer;
        writer << "(" << _xCoordinate << " , " << _yCoordinate << ")";
        return writer.str();
    }
    
    ~Point2D() {
        cout<< this->toString() << " destroy" << endl;
    }
};

class Line2D
{
private:
    Point2D _begin;
    Point2D _end;

public:
    Line2D() {
        cout << this->toString() << " cons" << endl;
    }
    Line2D(Point2D b, Point2D e) : _begin(b), _end(e) 
    {
        cout << this->toString() << " cons" << endl;
    }
    Line2D(float b1, float e1, float b2, float e2)
        : _begin(Point2D(b1, e1)), _end(Point2D(b2, e2)) 
    {
        cout << this->toString() << " cons" << endl;
    }

    std::string toString() {
        std::stringstream writer;
        writer << "Your 2D Line: " << _begin.toString() << " -> " << _end.toString();
        return writer.str();
    }
    ~Line2D() {
        cout<< this->toString() << "destroy" << endl;
    }
};

Many thanks in advance! This is also my first post in here so apologize any ‘silly’ mistakes.

Source: Windows Questions C++

LEAVE A COMMENT