Class operator ' s call without a copy (this class)



  • That's a good example. I just can't figure out why operator () It's fine without creating a copy of the class.

    #include <iostream>
    

    using namespace std;

    struct sq {
    int operator()(int x) const {
    return x * x;
    }
    };

    int main(){
    cout << sq()(5) << endl; // здесь должна быть синтаксическая ошибка. экземпляр класса пока не создан

    return 0;
    

    }

    Explain what my misconception is.


    Make it clear.

    #include <iostream>

    using namespace std;

    struct sq {
    sq(){ cout << "constructor " << endl; }

    int operator()(int x) const {
        return x * x;
    }
    
    int print(int i){
        return i;
    }
    

    };

    int main(){
    cout << sq()(5) << endl; // правильно. создается временный объект
    cout << sq.print(10) << endl; // не правильно. здесь ошибка. объект не создается

    return 0;
    

    }



  • sq()(5)
    

    This is where the designer is called. sq() and thus creates a temporary facility for which implementation is already under way operator() with argument 5♪ I don't see anything wrong.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2