1 year ago

#87590

test-img

salcan

Why can't I see an error when I let an lvalue reference constructor accept an rvalue in Visual Studio?

#include <iostream>
#include <type_traits>

using namespace std;

class Point
{
public:
    int x, y;
public:
    Point(int a, int b) : x(a), y(b) { cout << "Point()" << endl; }
    Point(Point& p) : x(p.x), y(p.y) { cout << "Point&" << endl; }
};

int main()
{
    Point p2 = Point(1, 2);  // no error.

    cout << "---" << endl;

    cout << is_copy_constructible<Point>::value << endl;           // 0
    cout << is_trivially_copy_constructible<Point>::value << endl; // 0
    cout << is_move_constructible<Point>::value << endl;           // 0
    cout << is_trivially_move_constructible<Point>::value << endl; // 0
}

I think that the Point object doesn't have any constructors that accept rvalue arguments, but when I compiled this code on Visual Studio, I couldn't see an error.

Instead, when I compiled this code with g++ compiler, I saw an error as below shown:

 cannot bind non-const lvalue reference of type 'Point&' to an rvalue of
 type 'Point'
   29 |     Point p3 = Point(2, 3);
      |                ^~~~~~~

constructor_with_lvalue_ref.cpp:16:18: note:   initializing argument 1 of 'Point::Point(Point&)' 
   16 |     Point(Point& p) : x(p.x), y(p.y) { cout << "Point&" << endl; }  
      |           ~~~~~~~^                                                  

I don't understand why I can't see an error on Visual Studio when I let an lvalue reference constructor accept an rvalue.

Can I make the Microsoft compiler make an error with this code?

c++

constructor

copy-constructor

value-categories

0 Answers

Your Answer

Accepted video resources