Who's right here? g++ or Visual Studio 2017?Visual Studio 2015 or 2017 does not discover unit testsVisual Studio 2017 error: Unable to start program, An operation is not legal in the current stateUnit Tests not discovered in Visual Studio 2017Can't enter c++ code on Visual Studio 2017Visual Studio 2017 - IntelliSense does not recognise identifiersInstalling pytz for Python for Visual Studio 2017Visual Studio 2017 command line promptHow to register “custom tool” with Visual Studio 2017 to make it work?Extract visual studio 2017 product keyVisual Studio 2017 loop auto-vectorization issue

Do we have C++20 ranges library in GCC 9?

Adding labels and comments to a matrix

Can my Serbian girlfriend apply for a UK Standard Visitor visa and stay for the whole 6 months?

Resize before convert or convert before resize?

Is there any good reason to write "it is easy to see"?

Is it safe to use two single-pole breakers for a 240v circuit?

Why doesn't Iron Man's action affect this person in Endgame?

Wireless headphones interfere with Wi-Fi signal on laptop

Why was my Canon Speedlite 600EX triggering other flashes?

Polynomial division: Is this trick obvious?

How to continually let my readers know what time it is in my story, in an organic way?

White foam around tubeless tires

Why are solar panels kept tilted?

Why are BJTs common in output stages of power amplifiers?

Is Valonqar prophecy unfulfilled?

What is this old US Air Force plane?

Is this possible when it comes to the relations of P, NP, NP-Hard and NP-Complete?

How to not get blinded by an attack at dawn

Can you pick an advanced rogue talent with the Extra Rogue Talent feat?

Can I say: "When was your train leaving?" if the train leaves in the future?

Smooth function that vanishes only on unit cube

Will the volt, ampere, ohm or other electrical units change on May 20th, 2019?

Are Allah and Hashem one and the same?

Problem in downloading videos using youtube-dl from unsupported sites



Who's right here? g++ or Visual Studio 2017?


Visual Studio 2015 or 2017 does not discover unit testsVisual Studio 2017 error: Unable to start program, An operation is not legal in the current stateUnit Tests not discovered in Visual Studio 2017Can't enter c++ code on Visual Studio 2017Visual Studio 2017 - IntelliSense does not recognise identifiersInstalling pytz for Python for Visual Studio 2017Visual Studio 2017 command line promptHow to register “custom tool” with Visual Studio 2017 to make it work?Extract visual studio 2017 product keyVisual Studio 2017 loop auto-vectorization issue






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








1















Recently I came across a funny "feature".
The code below compiles equally on both g++ and Visual Studio 2017.



#include <iostream>
#include <list>

int main()

std::list<int *> l;
int a = 1, b = 2;
l.emplace_back(&a);
auto p = l.front();
std::cout << p << 'n'; // prints x
l.erase(l.begin());
l.emplace_back(&b);
std::cout << p << 'n'; // prints x
std::cin.get();



However, if you change line



auto p = l.front();


to



auto & p = l.front();


Visual Studio still gives the same output (considering the address x may change, of course). However, now g++ gives me the output



x
x+4


Obviously, when passing the pointer by reference, g++ recognizes that the first element of the list now has a different value, which is a different address of the stack (offset + 4 compared to the initial one), while Visual Studio 2017 doesn't. So... who's broken?










share|improve this question






























    1















    Recently I came across a funny "feature".
    The code below compiles equally on both g++ and Visual Studio 2017.



    #include <iostream>
    #include <list>

    int main()

    std::list<int *> l;
    int a = 1, b = 2;
    l.emplace_back(&a);
    auto p = l.front();
    std::cout << p << 'n'; // prints x
    l.erase(l.begin());
    l.emplace_back(&b);
    std::cout << p << 'n'; // prints x
    std::cin.get();



    However, if you change line



    auto p = l.front();


    to



    auto & p = l.front();


    Visual Studio still gives the same output (considering the address x may change, of course). However, now g++ gives me the output



    x
    x+4


    Obviously, when passing the pointer by reference, g++ recognizes that the first element of the list now has a different value, which is a different address of the stack (offset + 4 compared to the initial one), while Visual Studio 2017 doesn't. So... who's broken?










    share|improve this question


























      1












      1








      1








      Recently I came across a funny "feature".
      The code below compiles equally on both g++ and Visual Studio 2017.



      #include <iostream>
      #include <list>

      int main()

      std::list<int *> l;
      int a = 1, b = 2;
      l.emplace_back(&a);
      auto p = l.front();
      std::cout << p << 'n'; // prints x
      l.erase(l.begin());
      l.emplace_back(&b);
      std::cout << p << 'n'; // prints x
      std::cin.get();



      However, if you change line



      auto p = l.front();


      to



      auto & p = l.front();


      Visual Studio still gives the same output (considering the address x may change, of course). However, now g++ gives me the output



      x
      x+4


      Obviously, when passing the pointer by reference, g++ recognizes that the first element of the list now has a different value, which is a different address of the stack (offset + 4 compared to the initial one), while Visual Studio 2017 doesn't. So... who's broken?










      share|improve this question
















      Recently I came across a funny "feature".
      The code below compiles equally on both g++ and Visual Studio 2017.



      #include <iostream>
      #include <list>

      int main()

      std::list<int *> l;
      int a = 1, b = 2;
      l.emplace_back(&a);
      auto p = l.front();
      std::cout << p << 'n'; // prints x
      l.erase(l.begin());
      l.emplace_back(&b);
      std::cout << p << 'n'; // prints x
      std::cin.get();



      However, if you change line



      auto p = l.front();


      to



      auto & p = l.front();


      Visual Studio still gives the same output (considering the address x may change, of course). However, now g++ gives me the output



      x
      x+4


      Obviously, when passing the pointer by reference, g++ recognizes that the first element of the list now has a different value, which is a different address of the stack (offset + 4 compared to the initial one), while Visual Studio 2017 doesn't. So... who's broken?







      c++ reference visual-studio-2017 g++ undefined-behavior






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 23 at 14:43









      songyuanyao

      95.6k11187256




      95.6k11187256










      asked Mar 23 at 14:20









      potatosaladpotatosalad

      134




      134






















          2 Answers
          2






          active

          oldest

          votes


















          5















          who's broken?




          Both are correct, because your code has undefined behavior.



          After auto & p = l.front();, you erased the element from the list, then p becomes dangled; any dereference on it leads to UB, means anything is possible.




          References and iterators to the erased elements are invalidated.







          share|improve this answer
































            4














            After l.erase(l.begin()); reference to first item previously obtained at auto & p = l.front(); becomes invalid and accessing value stored in p leads to Undefined Behavior. So it is your code that is broken.






            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
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55314667%2fwhos-right-here-g-or-visual-studio-2017%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              5















              who's broken?




              Both are correct, because your code has undefined behavior.



              After auto & p = l.front();, you erased the element from the list, then p becomes dangled; any dereference on it leads to UB, means anything is possible.




              References and iterators to the erased elements are invalidated.







              share|improve this answer





























                5















                who's broken?




                Both are correct, because your code has undefined behavior.



                After auto & p = l.front();, you erased the element from the list, then p becomes dangled; any dereference on it leads to UB, means anything is possible.




                References and iterators to the erased elements are invalidated.







                share|improve this answer



























                  5












                  5








                  5








                  who's broken?




                  Both are correct, because your code has undefined behavior.



                  After auto & p = l.front();, you erased the element from the list, then p becomes dangled; any dereference on it leads to UB, means anything is possible.




                  References and iterators to the erased elements are invalidated.







                  share|improve this answer
















                  who's broken?




                  Both are correct, because your code has undefined behavior.



                  After auto & p = l.front();, you erased the element from the list, then p becomes dangled; any dereference on it leads to UB, means anything is possible.




                  References and iterators to the erased elements are invalidated.








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 23 at 14:31

























                  answered Mar 23 at 14:26









                  songyuanyaosongyuanyao

                  95.6k11187256




                  95.6k11187256























                      4














                      After l.erase(l.begin()); reference to first item previously obtained at auto & p = l.front(); becomes invalid and accessing value stored in p leads to Undefined Behavior. So it is your code that is broken.






                      share|improve this answer



























                        4














                        After l.erase(l.begin()); reference to first item previously obtained at auto & p = l.front(); becomes invalid and accessing value stored in p leads to Undefined Behavior. So it is your code that is broken.






                        share|improve this answer

























                          4












                          4








                          4







                          After l.erase(l.begin()); reference to first item previously obtained at auto & p = l.front(); becomes invalid and accessing value stored in p leads to Undefined Behavior. So it is your code that is broken.






                          share|improve this answer













                          After l.erase(l.begin()); reference to first item previously obtained at auto & p = l.front(); becomes invalid and accessing value stored in p leads to Undefined Behavior. So it is your code that is broken.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 23 at 14:25









                          VTTVTT

                          27k42651




                          27k42651



























                              draft saved

                              draft discarded
















































                              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%2f55314667%2fwhos-right-here-g-or-visual-studio-2017%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

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현