Lifetime and usefulness of an object that is created inside an if statement in a method





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







0















This ic the class I want to use to understand destructors.



#include iostream
using namespace std;

class Student{
public:
Student(int num = 0)
{
id = num;
}
}


This is the method



void bar(int a)
{

if( a == 5)
Student S(5);

cout<<"after if"<<endl;

}


The thing is that if a = 5; object S of Student class is created and the object's life time ends with the if loop. The destructor called before the line after if. So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore? Or can they somehow be useful?










share|improve this question




















  • 1





    You can use them inside the loop, which is very useful.

    – molbdnilo
    Nov 16 '18 at 19:52






  • 2





    If you have a loop, not just an if statement, this is a great way to make sure a variable is reset to a known state at the beginning of each iteration.

    – user4581301
    Nov 16 '18 at 19:58











  • "So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore?" 1) Your example doesn't even contain a loop. 2) In your example, yes, it is useless. There are cases, however, where creating an object, with a lifetime limited to a particular scope would be useful (not mentioning the cases, where some object has purpose, only while being in some inner scope, one of the examples that comes to mind is: std::scoped_lock).

    – Algirdas Preidžius
    Nov 16 '18 at 20:20













  • If you have ever written any algorithm, you have most likely used primitives that lived only inside a loop. Were they useless? Is anything on the stack useless since it dies when the main ends (or before)?

    – Aziuth
    Nov 16 '18 at 20:28




















0















This ic the class I want to use to understand destructors.



#include iostream
using namespace std;

class Student{
public:
Student(int num = 0)
{
id = num;
}
}


This is the method



void bar(int a)
{

if( a == 5)
Student S(5);

cout<<"after if"<<endl;

}


The thing is that if a = 5; object S of Student class is created and the object's life time ends with the if loop. The destructor called before the line after if. So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore? Or can they somehow be useful?










share|improve this question




















  • 1





    You can use them inside the loop, which is very useful.

    – molbdnilo
    Nov 16 '18 at 19:52






  • 2





    If you have a loop, not just an if statement, this is a great way to make sure a variable is reset to a known state at the beginning of each iteration.

    – user4581301
    Nov 16 '18 at 19:58











  • "So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore?" 1) Your example doesn't even contain a loop. 2) In your example, yes, it is useless. There are cases, however, where creating an object, with a lifetime limited to a particular scope would be useful (not mentioning the cases, where some object has purpose, only while being in some inner scope, one of the examples that comes to mind is: std::scoped_lock).

    – Algirdas Preidžius
    Nov 16 '18 at 20:20













  • If you have ever written any algorithm, you have most likely used primitives that lived only inside a loop. Were they useless? Is anything on the stack useless since it dies when the main ends (or before)?

    – Aziuth
    Nov 16 '18 at 20:28
















0












0








0








This ic the class I want to use to understand destructors.



#include iostream
using namespace std;

class Student{
public:
Student(int num = 0)
{
id = num;
}
}


This is the method



void bar(int a)
{

if( a == 5)
Student S(5);

cout<<"after if"<<endl;

}


The thing is that if a = 5; object S of Student class is created and the object's life time ends with the if loop. The destructor called before the line after if. So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore? Or can they somehow be useful?










share|improve this question
















This ic the class I want to use to understand destructors.



#include iostream
using namespace std;

class Student{
public:
Student(int num = 0)
{
id = num;
}
}


This is the method



void bar(int a)
{

if( a == 5)
Student S(5);

cout<<"after if"<<endl;

}


The thing is that if a = 5; object S of Student class is created and the object's life time ends with the if loop. The destructor called before the line after if. So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore? Or can they somehow be useful?







c++ object destructor lifetime






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 19:53









Brian

66.8k799191




66.8k799191










asked Nov 16 '18 at 19:48









Crazy_Boy53Crazy_Boy53

916




916








  • 1





    You can use them inside the loop, which is very useful.

    – molbdnilo
    Nov 16 '18 at 19:52






  • 2





    If you have a loop, not just an if statement, this is a great way to make sure a variable is reset to a known state at the beginning of each iteration.

    – user4581301
    Nov 16 '18 at 19:58











  • "So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore?" 1) Your example doesn't even contain a loop. 2) In your example, yes, it is useless. There are cases, however, where creating an object, with a lifetime limited to a particular scope would be useful (not mentioning the cases, where some object has purpose, only while being in some inner scope, one of the examples that comes to mind is: std::scoped_lock).

    – Algirdas Preidžius
    Nov 16 '18 at 20:20













  • If you have ever written any algorithm, you have most likely used primitives that lived only inside a loop. Were they useless? Is anything on the stack useless since it dies when the main ends (or before)?

    – Aziuth
    Nov 16 '18 at 20:28
















  • 1





    You can use them inside the loop, which is very useful.

    – molbdnilo
    Nov 16 '18 at 19:52






  • 2





    If you have a loop, not just an if statement, this is a great way to make sure a variable is reset to a known state at the beginning of each iteration.

    – user4581301
    Nov 16 '18 at 19:58











  • "So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore?" 1) Your example doesn't even contain a loop. 2) In your example, yes, it is useless. There are cases, however, where creating an object, with a lifetime limited to a particular scope would be useful (not mentioning the cases, where some object has purpose, only while being in some inner scope, one of the examples that comes to mind is: std::scoped_lock).

    – Algirdas Preidžius
    Nov 16 '18 at 20:20













  • If you have ever written any algorithm, you have most likely used primitives that lived only inside a loop. Were they useless? Is anything on the stack useless since it dies when the main ends (or before)?

    – Aziuth
    Nov 16 '18 at 20:28










1




1





You can use them inside the loop, which is very useful.

– molbdnilo
Nov 16 '18 at 19:52





You can use them inside the loop, which is very useful.

– molbdnilo
Nov 16 '18 at 19:52




2




2





If you have a loop, not just an if statement, this is a great way to make sure a variable is reset to a known state at the beginning of each iteration.

– user4581301
Nov 16 '18 at 19:58





If you have a loop, not just an if statement, this is a great way to make sure a variable is reset to a known state at the beginning of each iteration.

– user4581301
Nov 16 '18 at 19:58













"So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore?" 1) Your example doesn't even contain a loop. 2) In your example, yes, it is useless. There are cases, however, where creating an object, with a lifetime limited to a particular scope would be useful (not mentioning the cases, where some object has purpose, only while being in some inner scope, one of the examples that comes to mind is: std::scoped_lock).

– Algirdas Preidžius
Nov 16 '18 at 20:20







"So shouldn't it mean that creating objects inside loops is just a waste of time because we can't use them anymore?" 1) Your example doesn't even contain a loop. 2) In your example, yes, it is useless. There are cases, however, where creating an object, with a lifetime limited to a particular scope would be useful (not mentioning the cases, where some object has purpose, only while being in some inner scope, one of the examples that comes to mind is: std::scoped_lock).

– Algirdas Preidžius
Nov 16 '18 at 20:20















If you have ever written any algorithm, you have most likely used primitives that lived only inside a loop. Were they useless? Is anything on the stack useless since it dies when the main ends (or before)?

– Aziuth
Nov 16 '18 at 20:28







If you have ever written any algorithm, you have most likely used primitives that lived only inside a loop. Were they useless? Is anything on the stack useless since it dies when the main ends (or before)?

– Aziuth
Nov 16 '18 at 20:28














1 Answer
1






active

oldest

votes


















0














I'm not entirely sure what you mean when you ask about usefulness.



If you only need an object to exist for a very short time but you still might want to hold on to that data, you can use std::shared_ptr to use smart pointers to dynamically allocate memory for the objects on the heap. The objects are very quick to access and is an easy way to make trivial use of them. You could do this with raw pointers but smart pointers are just safer, in that you won't ever get memory leaks from forgetting to delete a raw pointer:



std::shared_ptr<Student> stu_ptr;

if (a == 5)
stu_ptr = (new (Student(a)));

stu_ptr->someClassFunction();


stu_ptr still exists after the if statement. If you wanted to do multiple checks/conditions you could keep reassigning that stu_ptr or, due to the nature of shared pointers, you could make new shared pointers to the same Student object to fulfill other trivial calculations/functionalities.






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%2f53344442%2flifetime-and-usefulness-of-an-object-that-is-created-inside-an-if-statement-in-a%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I'm not entirely sure what you mean when you ask about usefulness.



    If you only need an object to exist for a very short time but you still might want to hold on to that data, you can use std::shared_ptr to use smart pointers to dynamically allocate memory for the objects on the heap. The objects are very quick to access and is an easy way to make trivial use of them. You could do this with raw pointers but smart pointers are just safer, in that you won't ever get memory leaks from forgetting to delete a raw pointer:



    std::shared_ptr<Student> stu_ptr;

    if (a == 5)
    stu_ptr = (new (Student(a)));

    stu_ptr->someClassFunction();


    stu_ptr still exists after the if statement. If you wanted to do multiple checks/conditions you could keep reassigning that stu_ptr or, due to the nature of shared pointers, you could make new shared pointers to the same Student object to fulfill other trivial calculations/functionalities.






    share|improve this answer




























      0














      I'm not entirely sure what you mean when you ask about usefulness.



      If you only need an object to exist for a very short time but you still might want to hold on to that data, you can use std::shared_ptr to use smart pointers to dynamically allocate memory for the objects on the heap. The objects are very quick to access and is an easy way to make trivial use of them. You could do this with raw pointers but smart pointers are just safer, in that you won't ever get memory leaks from forgetting to delete a raw pointer:



      std::shared_ptr<Student> stu_ptr;

      if (a == 5)
      stu_ptr = (new (Student(a)));

      stu_ptr->someClassFunction();


      stu_ptr still exists after the if statement. If you wanted to do multiple checks/conditions you could keep reassigning that stu_ptr or, due to the nature of shared pointers, you could make new shared pointers to the same Student object to fulfill other trivial calculations/functionalities.






      share|improve this answer


























        0












        0








        0







        I'm not entirely sure what you mean when you ask about usefulness.



        If you only need an object to exist for a very short time but you still might want to hold on to that data, you can use std::shared_ptr to use smart pointers to dynamically allocate memory for the objects on the heap. The objects are very quick to access and is an easy way to make trivial use of them. You could do this with raw pointers but smart pointers are just safer, in that you won't ever get memory leaks from forgetting to delete a raw pointer:



        std::shared_ptr<Student> stu_ptr;

        if (a == 5)
        stu_ptr = (new (Student(a)));

        stu_ptr->someClassFunction();


        stu_ptr still exists after the if statement. If you wanted to do multiple checks/conditions you could keep reassigning that stu_ptr or, due to the nature of shared pointers, you could make new shared pointers to the same Student object to fulfill other trivial calculations/functionalities.






        share|improve this answer













        I'm not entirely sure what you mean when you ask about usefulness.



        If you only need an object to exist for a very short time but you still might want to hold on to that data, you can use std::shared_ptr to use smart pointers to dynamically allocate memory for the objects on the heap. The objects are very quick to access and is an easy way to make trivial use of them. You could do this with raw pointers but smart pointers are just safer, in that you won't ever get memory leaks from forgetting to delete a raw pointer:



        std::shared_ptr<Student> stu_ptr;

        if (a == 5)
        stu_ptr = (new (Student(a)));

        stu_ptr->someClassFunction();


        stu_ptr still exists after the if statement. If you wanted to do multiple checks/conditions you could keep reassigning that stu_ptr or, due to the nature of shared pointers, you could make new shared pointers to the same Student object to fulfill other trivial calculations/functionalities.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 17 '18 at 3:36









        Collin AbrCollin Abr

        262




        262
































            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%2f53344442%2flifetime-and-usefulness-of-an-object-that-is-created-inside-an-if-statement-in-a%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

            Bressuire

            Vorschmack

            Quarantine