Is it idiomatic to construct against `this`How to implement the factory method pattern in C++ correctlyCommon Design for Console and GUIC++ composite reference to owner is corrupted when owner is movedHow do I delete pointer to (struct/object) without destroying pointers inside (struct/object)?c++ casting void* to int errorc++ accessing private members causes seg faultVoid pointer to a class object: Initialization inside a functionCasting vtable class to void pointer (C++)Why can't the compiler find the superclass's method?Packaging Parameter Packs

Apply MapThread to all but one variable

can anyone help me with this awful query plan?

Don’t seats that recline flat defeat the purpose of having seatbelts?

Which big number is bigger?

Can we say “you can pay when the order gets ready”?

bldc motor, esc and battery draw, nominal vs peak

"You've called the wrong number" or "You called the wrong number"

Was there a shared-world project before "Thieves World"?

How to prevent z-fighting in OpenSCAD?

First time hit, with spinach? A little bit?

Rivers without rain

Does tea made with boiling water cool faster than tea made with boiled (but still hot) water?

Why did C use the -> operator instead of reusing the . operator?

Aligning equation numbers vertically

Is Diceware more secure than a long passphrase?

How do I check if a string is entirely made of the same substring?

Can SQL Server create collisions in system generated constraint names?

What term is being referred to with "reflected-sound-of-underground-spirits"?

Dynamic SOQL query relationship with field visibility for Users

Was there a Viking Exchange as well as a Columbian one?

Function pointer with named arguments?

How do I deal with a coworker that keeps asking to make small superficial changes to a report, and it is seriously triggering my anxiety?

How to pronounce 'c++' in Spanish

A ​Note ​on ​N!



Is it idiomatic to construct against `this`


How to implement the factory method pattern in C++ correctlyCommon Design for Console and GUIC++ composite reference to owner is corrupted when owner is movedHow do I delete pointer to (struct/object) without destroying pointers inside (struct/object)?c++ casting void* to int errorc++ accessing private members causes seg faultVoid pointer to a class object: Initialization inside a functionCasting vtable class to void pointer (C++)Why can't the compiler find the superclass's method?Packaging Parameter Packs






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








11















When making a curses version of Snake, I found that the this pointer was bindable for reconstruction from inside an 'update' method.



The issue with this is that, although very convenient (saves having to rebind 'player' in a game object), it doesn't feel particularly idiomatic.



Using the snake as an example, we'd be destroying it and reconstructing it as we're inside a method call on the initial(?) snake.



Here's an example of rebinding this in some struct A:



struct A

int first;
A(int first) : first(first);
void method(int i);
;

void A::method(int i)

*this = A(i);










share|improve this question









New contributor




Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    It's calling the constructor that takes and int creating a temporary A then the assignment operator

    – Richard Critten
    8 hours ago












  • @JohnKugelman I'd be tempted, to avoid writing an operator= to match each constructor.

    – Caleth
    7 hours ago






  • 2





    I definitely use that to share code between functions. Especially overloaded operators. Particularly when implementing copy and move operators/constructors. And sometimes when writing iterators sharing functionality between preincrement and postincrement operators.

    – Galik
    7 hours ago






  • 7





    I would use the explicit keyword to make this illegal unless explicitly asked for. Having this conversion being implicitly allowed is asking for trouble.

    – Jesper Juhl
    7 hours ago


















11















When making a curses version of Snake, I found that the this pointer was bindable for reconstruction from inside an 'update' method.



The issue with this is that, although very convenient (saves having to rebind 'player' in a game object), it doesn't feel particularly idiomatic.



Using the snake as an example, we'd be destroying it and reconstructing it as we're inside a method call on the initial(?) snake.



Here's an example of rebinding this in some struct A:



struct A

int first;
A(int first) : first(first);
void method(int i);
;

void A::method(int i)

*this = A(i);










share|improve this question









New contributor




Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    It's calling the constructor that takes and int creating a temporary A then the assignment operator

    – Richard Critten
    8 hours ago












  • @JohnKugelman I'd be tempted, to avoid writing an operator= to match each constructor.

    – Caleth
    7 hours ago






  • 2





    I definitely use that to share code between functions. Especially overloaded operators. Particularly when implementing copy and move operators/constructors. And sometimes when writing iterators sharing functionality between preincrement and postincrement operators.

    – Galik
    7 hours ago






  • 7





    I would use the explicit keyword to make this illegal unless explicitly asked for. Having this conversion being implicitly allowed is asking for trouble.

    – Jesper Juhl
    7 hours ago














11












11








11


0






When making a curses version of Snake, I found that the this pointer was bindable for reconstruction from inside an 'update' method.



The issue with this is that, although very convenient (saves having to rebind 'player' in a game object), it doesn't feel particularly idiomatic.



Using the snake as an example, we'd be destroying it and reconstructing it as we're inside a method call on the initial(?) snake.



Here's an example of rebinding this in some struct A:



struct A

int first;
A(int first) : first(first);
void method(int i);
;

void A::method(int i)

*this = A(i);










share|improve this question









New contributor




Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












When making a curses version of Snake, I found that the this pointer was bindable for reconstruction from inside an 'update' method.



The issue with this is that, although very convenient (saves having to rebind 'player' in a game object), it doesn't feel particularly idiomatic.



Using the snake as an example, we'd be destroying it and reconstructing it as we're inside a method call on the initial(?) snake.



Here's an example of rebinding this in some struct A:



struct A

int first;
A(int first) : first(first);
void method(int i);
;

void A::method(int i)

*this = A(i);







c++






share|improve this question









New contributor




Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 3 hours ago







Catamondium













New contributor




Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 8 hours ago









CatamondiumCatamondium

636




636




New contributor




Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Catamondium is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1





    It's calling the constructor that takes and int creating a temporary A then the assignment operator

    – Richard Critten
    8 hours ago












  • @JohnKugelman I'd be tempted, to avoid writing an operator= to match each constructor.

    – Caleth
    7 hours ago






  • 2





    I definitely use that to share code between functions. Especially overloaded operators. Particularly when implementing copy and move operators/constructors. And sometimes when writing iterators sharing functionality between preincrement and postincrement operators.

    – Galik
    7 hours ago






  • 7





    I would use the explicit keyword to make this illegal unless explicitly asked for. Having this conversion being implicitly allowed is asking for trouble.

    – Jesper Juhl
    7 hours ago













  • 1





    It's calling the constructor that takes and int creating a temporary A then the assignment operator

    – Richard Critten
    8 hours ago












  • @JohnKugelman I'd be tempted, to avoid writing an operator= to match each constructor.

    – Caleth
    7 hours ago






  • 2





    I definitely use that to share code between functions. Especially overloaded operators. Particularly when implementing copy and move operators/constructors. And sometimes when writing iterators sharing functionality between preincrement and postincrement operators.

    – Galik
    7 hours ago






  • 7





    I would use the explicit keyword to make this illegal unless explicitly asked for. Having this conversion being implicitly allowed is asking for trouble.

    – Jesper Juhl
    7 hours ago








1




1





It's calling the constructor that takes and int creating a temporary A then the assignment operator

– Richard Critten
8 hours ago






It's calling the constructor that takes and int creating a temporary A then the assignment operator

– Richard Critten
8 hours ago














@JohnKugelman I'd be tempted, to avoid writing an operator= to match each constructor.

– Caleth
7 hours ago





@JohnKugelman I'd be tempted, to avoid writing an operator= to match each constructor.

– Caleth
7 hours ago




2




2





I definitely use that to share code between functions. Especially overloaded operators. Particularly when implementing copy and move operators/constructors. And sometimes when writing iterators sharing functionality between preincrement and postincrement operators.

– Galik
7 hours ago





I definitely use that to share code between functions. Especially overloaded operators. Particularly when implementing copy and move operators/constructors. And sometimes when writing iterators sharing functionality between preincrement and postincrement operators.

– Galik
7 hours ago




7




7





I would use the explicit keyword to make this illegal unless explicitly asked for. Having this conversion being implicitly allowed is asking for trouble.

– Jesper Juhl
7 hours ago






I would use the explicit keyword to make this illegal unless explicitly asked for. Having this conversion being implicitly allowed is asking for trouble.

– Jesper Juhl
7 hours ago













3 Answers
3






active

oldest

votes


















19














It's legal, but if I saw it I would question whether the author knew what they were doing: Did they really mean to invoke this->operator=()? Surely there's a better way to do... whatever it is they're trying to do.



In your case, *this = i is equivalent to this->operator=(i). Since there's no operator=(int) defined, it uses the default assignment operator and the A(int) constructor to perform this->operator=(A(i)). The net effect is exactly the same as if you had written:



this->first = i;


Why didn't they just assign to first directly? I'd be asking.



If for some reason you do want all those steps, I'd at least make the implicit A(int) construction explicit:



*this = A(i);





share|improve this answer




















  • 8





    On reading this code I'd assume it was one of those unfortunate cases where the compiler missed issuing a warning on code that obviously isn't doing what the programmer wanted. And then on the code review I'd point out he wouldn't have had this problem if he had declared the single-arg constructor explicit.

    – davidbak
    7 hours ago











  • Just for additional clarity, the intent was more-so the copy assignment and temporary destruction part of this answer. The implicit constructor call as a conversion was incidental. I'll add an edit to clarify. Otherwise, thank you.

    – Catamondium
    3 hours ago



















9














*this = i; implicitly constructs new instance of A as A::A(int) is not an explicit constructor and therefore creates the implicit conversion from int to A. *this = i; then calls default A::operator= with this new instance of A constructed from i. Then the new instance of A is destroyed.



So the code *this = i; is equivalent to operator=(A(i)); in your case.



It's legal to do so, but the code readability suffers from such a big amount of implicit actions.






share|improve this answer
































    6














    You aren't destroying the object pointed to by this, you are calling it's operator=, which will copy first from a temporary initialised from i. You destroy the temporary after the assignment.



    It might be clearer to write an A& operator=(int) which had the same effect.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );






      Catamondium is a new contributor. Be nice, and check out our Code of Conduct.









      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55871308%2fis-it-idiomatic-to-construct-against-this%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      19














      It's legal, but if I saw it I would question whether the author knew what they were doing: Did they really mean to invoke this->operator=()? Surely there's a better way to do... whatever it is they're trying to do.



      In your case, *this = i is equivalent to this->operator=(i). Since there's no operator=(int) defined, it uses the default assignment operator and the A(int) constructor to perform this->operator=(A(i)). The net effect is exactly the same as if you had written:



      this->first = i;


      Why didn't they just assign to first directly? I'd be asking.



      If for some reason you do want all those steps, I'd at least make the implicit A(int) construction explicit:



      *this = A(i);





      share|improve this answer




















      • 8





        On reading this code I'd assume it was one of those unfortunate cases where the compiler missed issuing a warning on code that obviously isn't doing what the programmer wanted. And then on the code review I'd point out he wouldn't have had this problem if he had declared the single-arg constructor explicit.

        – davidbak
        7 hours ago











      • Just for additional clarity, the intent was more-so the copy assignment and temporary destruction part of this answer. The implicit constructor call as a conversion was incidental. I'll add an edit to clarify. Otherwise, thank you.

        – Catamondium
        3 hours ago
















      19














      It's legal, but if I saw it I would question whether the author knew what they were doing: Did they really mean to invoke this->operator=()? Surely there's a better way to do... whatever it is they're trying to do.



      In your case, *this = i is equivalent to this->operator=(i). Since there's no operator=(int) defined, it uses the default assignment operator and the A(int) constructor to perform this->operator=(A(i)). The net effect is exactly the same as if you had written:



      this->first = i;


      Why didn't they just assign to first directly? I'd be asking.



      If for some reason you do want all those steps, I'd at least make the implicit A(int) construction explicit:



      *this = A(i);





      share|improve this answer




















      • 8





        On reading this code I'd assume it was one of those unfortunate cases where the compiler missed issuing a warning on code that obviously isn't doing what the programmer wanted. And then on the code review I'd point out he wouldn't have had this problem if he had declared the single-arg constructor explicit.

        – davidbak
        7 hours ago











      • Just for additional clarity, the intent was more-so the copy assignment and temporary destruction part of this answer. The implicit constructor call as a conversion was incidental. I'll add an edit to clarify. Otherwise, thank you.

        – Catamondium
        3 hours ago














      19












      19








      19







      It's legal, but if I saw it I would question whether the author knew what they were doing: Did they really mean to invoke this->operator=()? Surely there's a better way to do... whatever it is they're trying to do.



      In your case, *this = i is equivalent to this->operator=(i). Since there's no operator=(int) defined, it uses the default assignment operator and the A(int) constructor to perform this->operator=(A(i)). The net effect is exactly the same as if you had written:



      this->first = i;


      Why didn't they just assign to first directly? I'd be asking.



      If for some reason you do want all those steps, I'd at least make the implicit A(int) construction explicit:



      *this = A(i);





      share|improve this answer















      It's legal, but if I saw it I would question whether the author knew what they were doing: Did they really mean to invoke this->operator=()? Surely there's a better way to do... whatever it is they're trying to do.



      In your case, *this = i is equivalent to this->operator=(i). Since there's no operator=(int) defined, it uses the default assignment operator and the A(int) constructor to perform this->operator=(A(i)). The net effect is exactly the same as if you had written:



      this->first = i;


      Why didn't they just assign to first directly? I'd be asking.



      If for some reason you do want all those steps, I'd at least make the implicit A(int) construction explicit:



      *this = A(i);






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 7 hours ago

























      answered 7 hours ago









      John KugelmanJohn Kugelman

      250k54407461




      250k54407461







      • 8





        On reading this code I'd assume it was one of those unfortunate cases where the compiler missed issuing a warning on code that obviously isn't doing what the programmer wanted. And then on the code review I'd point out he wouldn't have had this problem if he had declared the single-arg constructor explicit.

        – davidbak
        7 hours ago











      • Just for additional clarity, the intent was more-so the copy assignment and temporary destruction part of this answer. The implicit constructor call as a conversion was incidental. I'll add an edit to clarify. Otherwise, thank you.

        – Catamondium
        3 hours ago













      • 8





        On reading this code I'd assume it was one of those unfortunate cases where the compiler missed issuing a warning on code that obviously isn't doing what the programmer wanted. And then on the code review I'd point out he wouldn't have had this problem if he had declared the single-arg constructor explicit.

        – davidbak
        7 hours ago











      • Just for additional clarity, the intent was more-so the copy assignment and temporary destruction part of this answer. The implicit constructor call as a conversion was incidental. I'll add an edit to clarify. Otherwise, thank you.

        – Catamondium
        3 hours ago








      8




      8





      On reading this code I'd assume it was one of those unfortunate cases where the compiler missed issuing a warning on code that obviously isn't doing what the programmer wanted. And then on the code review I'd point out he wouldn't have had this problem if he had declared the single-arg constructor explicit.

      – davidbak
      7 hours ago





      On reading this code I'd assume it was one of those unfortunate cases where the compiler missed issuing a warning on code that obviously isn't doing what the programmer wanted. And then on the code review I'd point out he wouldn't have had this problem if he had declared the single-arg constructor explicit.

      – davidbak
      7 hours ago













      Just for additional clarity, the intent was more-so the copy assignment and temporary destruction part of this answer. The implicit constructor call as a conversion was incidental. I'll add an edit to clarify. Otherwise, thank you.

      – Catamondium
      3 hours ago






      Just for additional clarity, the intent was more-so the copy assignment and temporary destruction part of this answer. The implicit constructor call as a conversion was incidental. I'll add an edit to clarify. Otherwise, thank you.

      – Catamondium
      3 hours ago














      9














      *this = i; implicitly constructs new instance of A as A::A(int) is not an explicit constructor and therefore creates the implicit conversion from int to A. *this = i; then calls default A::operator= with this new instance of A constructed from i. Then the new instance of A is destroyed.



      So the code *this = i; is equivalent to operator=(A(i)); in your case.



      It's legal to do so, but the code readability suffers from such a big amount of implicit actions.






      share|improve this answer





























        9














        *this = i; implicitly constructs new instance of A as A::A(int) is not an explicit constructor and therefore creates the implicit conversion from int to A. *this = i; then calls default A::operator= with this new instance of A constructed from i. Then the new instance of A is destroyed.



        So the code *this = i; is equivalent to operator=(A(i)); in your case.



        It's legal to do so, but the code readability suffers from such a big amount of implicit actions.






        share|improve this answer



























          9












          9








          9







          *this = i; implicitly constructs new instance of A as A::A(int) is not an explicit constructor and therefore creates the implicit conversion from int to A. *this = i; then calls default A::operator= with this new instance of A constructed from i. Then the new instance of A is destroyed.



          So the code *this = i; is equivalent to operator=(A(i)); in your case.



          It's legal to do so, but the code readability suffers from such a big amount of implicit actions.






          share|improve this answer















          *this = i; implicitly constructs new instance of A as A::A(int) is not an explicit constructor and therefore creates the implicit conversion from int to A. *this = i; then calls default A::operator= with this new instance of A constructed from i. Then the new instance of A is destroyed.



          So the code *this = i; is equivalent to operator=(A(i)); in your case.



          It's legal to do so, but the code readability suffers from such a big amount of implicit actions.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 7 hours ago

























          answered 7 hours ago









          OliortOliort

          489313




          489313





















              6














              You aren't destroying the object pointed to by this, you are calling it's operator=, which will copy first from a temporary initialised from i. You destroy the temporary after the assignment.



              It might be clearer to write an A& operator=(int) which had the same effect.






              share|improve this answer



























                6














                You aren't destroying the object pointed to by this, you are calling it's operator=, which will copy first from a temporary initialised from i. You destroy the temporary after the assignment.



                It might be clearer to write an A& operator=(int) which had the same effect.






                share|improve this answer

























                  6












                  6








                  6







                  You aren't destroying the object pointed to by this, you are calling it's operator=, which will copy first from a temporary initialised from i. You destroy the temporary after the assignment.



                  It might be clearer to write an A& operator=(int) which had the same effect.






                  share|improve this answer













                  You aren't destroying the object pointed to by this, you are calling it's operator=, which will copy first from a temporary initialised from i. You destroy the temporary after the assignment.



                  It might be clearer to write an A& operator=(int) which had the same effect.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 7 hours ago









                  CalethCaleth

                  19.2k22142




                  19.2k22142




















                      Catamondium is a new contributor. Be nice, and check out our Code of Conduct.









                      draft saved

                      draft discarded


















                      Catamondium is a new contributor. Be nice, and check out our Code of Conduct.












                      Catamondium is a new contributor. Be nice, and check out our Code of Conduct.











                      Catamondium is a new contributor. Be nice, and check out our Code of Conduct.














                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55871308%2fis-it-idiomatic-to-construct-against-this%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Nidaros erkebispedøme

                      Birsay

                      Where did Arya get these scars? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Favourite questions and answers from the 1st quarter of 2019Why did Arya refuse to end it?Has the pronunciation of Arya Stark's name changed?Has Arya forgiven people?Why did Arya Stark lose her vision?Why can Arya still use the faces?Has the Narrow Sea become narrower?Does Arya Stark know how to make poisons outside of the House of Black and White?Why did Nymeria leave Arya?Why did Arya not kill the Lannister soldiers she encountered in the Riverlands?What is the current canonical age of Sansa, Bran and Arya Stark?