Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-76021

Dangerous behavior of instanceof or ability to assign objects of "different types"

    XMLWordPrintable

Details

    • 28eb0caec23e0c315056cb035535b8806ccb0f37 (qt/qtdeclarative/5.14)

    Description

      With this example code:

       

      //SpecialRectangle1.qml

      import QtQuick 2.0
      
      Rectangle {
          readonly property bool fakeProperty: false
      
          implicitWidth: 100
          implicitHeight: 100
      
          Rectangle {
              anchors.centerIn: parent
              width: 10
              height: 10
              color: "red"
          }
      }
      

      //SpecialRectangle2.qml

      import QtQuick 2.0
      
      Rectangle {
          implicitWidth: 100
          implicitHeight: 100
      
          Rectangle {
              anchors.centerIn: parent
              width: 10
              height: 10
              color: "red"
          }
      }
      

      //main.qml

      import QtQuick 2.9
      import QtQuick.Controls 2.2
      
      ApplicationWindow {
          property SpecialRectangle1 rect1: SpecialRectangle1 {}
          property SpecialRectangle2 rect2: SpecialRectangle2 {}
          //property SpecialRectangle1 rect3: Rectangle {} //You can activate this line if fakeProperty from SpecialRectangle1 is deleted
          property SpecialRectangle2 rect4: Rectangle {}
      
          visible: true
          width: 640
          height: 480
      
          Text {
              anchors.centerIn: parent
              text: "%1 %2".arg(rect1 instanceof SpecialRectangle2).arg(rect2 instanceof SpecialRectangle1)
          }
      }
      

      instanceof return true despite rect1 is no instance of SpecialRectangle2... It works similarly with the assignment of properties, where it is theoretically possible to assign Rectangle to SpecialRectangle2.

      I understand that these types actually have the same API but they can have different content. For me, defining a component in a separate file suggests that it is a separate type ... Such behavior of instanceof can be dangerous, because adding or removing properties, signals etc can lead to improper functioning of algorithms that use instanceof to distinguish objects.

      Attachments

        Issue Links

          No reviews matched the request. Check your Options in the drop-down menu of this sections header.

          Activity

            People

              ulherman Ulf Hermann
              permotion88 Karol Polak
              Votes:
              1 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:

                Gerrit Reviews

                  There are no open Gerrit changes