Why would a new[] expression ever invoke a destructor?












36















From the C++17 standard (draft here), [expr.new]:




If the new-expression creates an object or an array of objects of class type, access and ambiguity control are done for the allocation function, the deallocation function, and the constructor. If the new-expression creates an array of objects of class type, the destructor is potentially invoked.




Why would new invoke a destructor? It's new, after all. It isn't delete.










share|improve this question





























    36















    From the C++17 standard (draft here), [expr.new]:




    If the new-expression creates an object or an array of objects of class type, access and ambiguity control are done for the allocation function, the deallocation function, and the constructor. If the new-expression creates an array of objects of class type, the destructor is potentially invoked.




    Why would new invoke a destructor? It's new, after all. It isn't delete.










    share|improve this question



























      36












      36








      36


      1






      From the C++17 standard (draft here), [expr.new]:




      If the new-expression creates an object or an array of objects of class type, access and ambiguity control are done for the allocation function, the deallocation function, and the constructor. If the new-expression creates an array of objects of class type, the destructor is potentially invoked.




      Why would new invoke a destructor? It's new, after all. It isn't delete.










      share|improve this question
















      From the C++17 standard (draft here), [expr.new]:




      If the new-expression creates an object or an array of objects of class type, access and ambiguity control are done for the allocation function, the deallocation function, and the constructor. If the new-expression creates an array of objects of class type, the destructor is potentially invoked.




      Why would new invoke a destructor? It's new, after all. It isn't delete.







      c++ c++17 new-operator






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 22 at 20:44









      Cody Gray

      195k35383475




      195k35383475










      asked Mar 22 at 20:32









      thbthb

      8,90532457




      8,90532457
























          3 Answers
          3






          active

          oldest

          votes


















          54














          If construction of any object in the buffer throws an exception, the previously constructed objects must be destructed. That requires an available destructor.






          share|improve this answer


























          • For clarification: Does this mean that a new (non-array) could also potentially call the destructor? I believe so from what I am seeing but wanted to ensure myself it is true.

            – Daniel Robert Miller
            yesterday











          • @DanielRobertMiller - An object not fully constructed won't have its destructor called. A non-array new doesn't require an available d'tor.

            – StoryTeller
            yesterday





















          12














          You have not considered the word "potentially" in the quote you have mentioned from the standard.

          It means that there is a possibility that invocation of the destructor can happen. And it will happen if construction of any object in the array throws an exception.



          Combined with the following quote from [class.dtor]/12.4 which mentions [expr.new], this becomes clear.




          In each case, the context of the invocation is the context of the construction of the object. A destructor is also invoked implicitly through use of a delete-expression for a constructed object allocated by a new-expression; the context of the invocation is the delete-expression. [ Note: An array of class type contains several subobjects for each of which the destructor is invoked.  — end note ] A destructor can also be invoked explicitly. A destructor is potentially invoked if it is invoked or as specified in [expr.new], [class.base.init], and [except.throw]. A program is ill-formed if a destructor that is potentially invoked is deleted or not accessible from the context of the invocation.







          share|improve this answer
























          • It is a bit too wordy for a simple answer though...

            – sophros
            yesterday



















          7














          In action:



          #include <iostream>

          int counter;

          class Destruct
          {
          public:
          Destruct()
          {
          if (counter++ > 5)
          throw counter;
          }

          ~Destruct()
          {
          std::cout << "Dtor calledn";
          }
          };

          int main()
          {
          try
          {
          new Destruct[10];
          }
          catch (...){}
          }


          You'll see output something like:



          Dtor called
          Dtor called
          Dtor called
          Dtor called
          Dtor called
          Dtor called





          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%2f55307381%2fwhy-would-a-new-expression-ever-invoke-a-destructor%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









            54














            If construction of any object in the buffer throws an exception, the previously constructed objects must be destructed. That requires an available destructor.






            share|improve this answer


























            • For clarification: Does this mean that a new (non-array) could also potentially call the destructor? I believe so from what I am seeing but wanted to ensure myself it is true.

              – Daniel Robert Miller
              yesterday











            • @DanielRobertMiller - An object not fully constructed won't have its destructor called. A non-array new doesn't require an available d'tor.

              – StoryTeller
              yesterday


















            54














            If construction of any object in the buffer throws an exception, the previously constructed objects must be destructed. That requires an available destructor.






            share|improve this answer


























            • For clarification: Does this mean that a new (non-array) could also potentially call the destructor? I believe so from what I am seeing but wanted to ensure myself it is true.

              – Daniel Robert Miller
              yesterday











            • @DanielRobertMiller - An object not fully constructed won't have its destructor called. A non-array new doesn't require an available d'tor.

              – StoryTeller
              yesterday
















            54












            54








            54







            If construction of any object in the buffer throws an exception, the previously constructed objects must be destructed. That requires an available destructor.






            share|improve this answer















            If construction of any object in the buffer throws an exception, the previously constructed objects must be destructed. That requires an available destructor.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 22 at 20:35









            Sombrero Chicken

            24.7k33281




            24.7k33281










            answered Mar 22 at 20:34









            StoryTellerStoryTeller

            104k12218281




            104k12218281













            • For clarification: Does this mean that a new (non-array) could also potentially call the destructor? I believe so from what I am seeing but wanted to ensure myself it is true.

              – Daniel Robert Miller
              yesterday











            • @DanielRobertMiller - An object not fully constructed won't have its destructor called. A non-array new doesn't require an available d'tor.

              – StoryTeller
              yesterday





















            • For clarification: Does this mean that a new (non-array) could also potentially call the destructor? I believe so from what I am seeing but wanted to ensure myself it is true.

              – Daniel Robert Miller
              yesterday











            • @DanielRobertMiller - An object not fully constructed won't have its destructor called. A non-array new doesn't require an available d'tor.

              – StoryTeller
              yesterday



















            For clarification: Does this mean that a new (non-array) could also potentially call the destructor? I believe so from what I am seeing but wanted to ensure myself it is true.

            – Daniel Robert Miller
            yesterday





            For clarification: Does this mean that a new (non-array) could also potentially call the destructor? I believe so from what I am seeing but wanted to ensure myself it is true.

            – Daniel Robert Miller
            yesterday













            @DanielRobertMiller - An object not fully constructed won't have its destructor called. A non-array new doesn't require an available d'tor.

            – StoryTeller
            yesterday







            @DanielRobertMiller - An object not fully constructed won't have its destructor called. A non-array new doesn't require an available d'tor.

            – StoryTeller
            yesterday















            12














            You have not considered the word "potentially" in the quote you have mentioned from the standard.

            It means that there is a possibility that invocation of the destructor can happen. And it will happen if construction of any object in the array throws an exception.



            Combined with the following quote from [class.dtor]/12.4 which mentions [expr.new], this becomes clear.




            In each case, the context of the invocation is the context of the construction of the object. A destructor is also invoked implicitly through use of a delete-expression for a constructed object allocated by a new-expression; the context of the invocation is the delete-expression. [ Note: An array of class type contains several subobjects for each of which the destructor is invoked.  — end note ] A destructor can also be invoked explicitly. A destructor is potentially invoked if it is invoked or as specified in [expr.new], [class.base.init], and [except.throw]. A program is ill-formed if a destructor that is potentially invoked is deleted or not accessible from the context of the invocation.







            share|improve this answer
























            • It is a bit too wordy for a simple answer though...

              – sophros
              yesterday
















            12














            You have not considered the word "potentially" in the quote you have mentioned from the standard.

            It means that there is a possibility that invocation of the destructor can happen. And it will happen if construction of any object in the array throws an exception.



            Combined with the following quote from [class.dtor]/12.4 which mentions [expr.new], this becomes clear.




            In each case, the context of the invocation is the context of the construction of the object. A destructor is also invoked implicitly through use of a delete-expression for a constructed object allocated by a new-expression; the context of the invocation is the delete-expression. [ Note: An array of class type contains several subobjects for each of which the destructor is invoked.  — end note ] A destructor can also be invoked explicitly. A destructor is potentially invoked if it is invoked or as specified in [expr.new], [class.base.init], and [except.throw]. A program is ill-formed if a destructor that is potentially invoked is deleted or not accessible from the context of the invocation.







            share|improve this answer
























            • It is a bit too wordy for a simple answer though...

              – sophros
              yesterday














            12












            12








            12







            You have not considered the word "potentially" in the quote you have mentioned from the standard.

            It means that there is a possibility that invocation of the destructor can happen. And it will happen if construction of any object in the array throws an exception.



            Combined with the following quote from [class.dtor]/12.4 which mentions [expr.new], this becomes clear.




            In each case, the context of the invocation is the context of the construction of the object. A destructor is also invoked implicitly through use of a delete-expression for a constructed object allocated by a new-expression; the context of the invocation is the delete-expression. [ Note: An array of class type contains several subobjects for each of which the destructor is invoked.  — end note ] A destructor can also be invoked explicitly. A destructor is potentially invoked if it is invoked or as specified in [expr.new], [class.base.init], and [except.throw]. A program is ill-formed if a destructor that is potentially invoked is deleted or not accessible from the context of the invocation.







            share|improve this answer













            You have not considered the word "potentially" in the quote you have mentioned from the standard.

            It means that there is a possibility that invocation of the destructor can happen. And it will happen if construction of any object in the array throws an exception.



            Combined with the following quote from [class.dtor]/12.4 which mentions [expr.new], this becomes clear.




            In each case, the context of the invocation is the context of the construction of the object. A destructor is also invoked implicitly through use of a delete-expression for a constructed object allocated by a new-expression; the context of the invocation is the delete-expression. [ Note: An array of class type contains several subobjects for each of which the destructor is invoked.  — end note ] A destructor can also be invoked explicitly. A destructor is potentially invoked if it is invoked or as specified in [expr.new], [class.base.init], and [except.throw]. A program is ill-formed if a destructor that is potentially invoked is deleted or not accessible from the context of the invocation.








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 23 at 7:59









            P.WP.W

            17.6k41657




            17.6k41657













            • It is a bit too wordy for a simple answer though...

              – sophros
              yesterday



















            • It is a bit too wordy for a simple answer though...

              – sophros
              yesterday

















            It is a bit too wordy for a simple answer though...

            – sophros
            yesterday





            It is a bit too wordy for a simple answer though...

            – sophros
            yesterday











            7














            In action:



            #include <iostream>

            int counter;

            class Destruct
            {
            public:
            Destruct()
            {
            if (counter++ > 5)
            throw counter;
            }

            ~Destruct()
            {
            std::cout << "Dtor calledn";
            }
            };

            int main()
            {
            try
            {
            new Destruct[10];
            }
            catch (...){}
            }


            You'll see output something like:



            Dtor called
            Dtor called
            Dtor called
            Dtor called
            Dtor called
            Dtor called





            share|improve this answer




























              7














              In action:



              #include <iostream>

              int counter;

              class Destruct
              {
              public:
              Destruct()
              {
              if (counter++ > 5)
              throw counter;
              }

              ~Destruct()
              {
              std::cout << "Dtor calledn";
              }
              };

              int main()
              {
              try
              {
              new Destruct[10];
              }
              catch (...){}
              }


              You'll see output something like:



              Dtor called
              Dtor called
              Dtor called
              Dtor called
              Dtor called
              Dtor called





              share|improve this answer


























                7












                7








                7







                In action:



                #include <iostream>

                int counter;

                class Destruct
                {
                public:
                Destruct()
                {
                if (counter++ > 5)
                throw counter;
                }

                ~Destruct()
                {
                std::cout << "Dtor calledn";
                }
                };

                int main()
                {
                try
                {
                new Destruct[10];
                }
                catch (...){}
                }


                You'll see output something like:



                Dtor called
                Dtor called
                Dtor called
                Dtor called
                Dtor called
                Dtor called





                share|improve this answer













                In action:



                #include <iostream>

                int counter;

                class Destruct
                {
                public:
                Destruct()
                {
                if (counter++ > 5)
                throw counter;
                }

                ~Destruct()
                {
                std::cout << "Dtor calledn";
                }
                };

                int main()
                {
                try
                {
                new Destruct[10];
                }
                catch (...){}
                }


                You'll see output something like:



                Dtor called
                Dtor called
                Dtor called
                Dtor called
                Dtor called
                Dtor called






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 2 days ago









                AjayAjay

                13.6k84179




                13.6k84179






























                    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%2f55307381%2fwhy-would-a-new-expression-ever-invoke-a-destructor%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

                    If I really need a card on my start hand, how many mulligans make sense? [duplicate]

                    Alcedinidae

                    Can an atomic nucleus contain both particles and antiparticles? [duplicate]