Is there a way to make member function NOT callable from constructor?What are the differences between a pointer variable and a reference variable in C++?Can I call a constructor from another constructor (do constructor chaining) in C++?Throwing exceptions from constructorsHow do I call ::std::make_shared on a class with only protected or private constructors?Calling a base member in constructor in multiple inheritance in C++Equality-compare std::weak_ptrClass inheritance: Constructor and member functions of class not recognized by compilerHow does shared_ptr<T> detect that T derives from enable_shared_from_this<T>?enable_shared_from_this derived class methods are undefined referenceDefault move constructor with mutex member

"listening to me about as much as you're listening to this pole here"

Ideas for 3rd eye abilities

Are cabin dividers used to "hide" the flex of the airplane?

Email Account under attack (really) - anything I can do?

How to deal with fear of taking dependencies

Where else does the Shulchan Aruch quote an authority by name?

(Soft question) does light intensity oscillate really fast since it is a wave?

Does it makes sense to buy a new cycle to learn riding?

Landlord wants to switch my lease to a "Land contract" to "get back at the city"

Find the number of surjections from A to B.

Does a dangling wire really electrocute me if I'm standing in water?

What happens when a metallic dragon and a chromatic dragon mate?

Is a vector space a subspace of itself?

"My colleague's body is amazing"

Is it legal to have the "// (c) 2019 John Smith" header in all files when there are hundreds of contributors?

Landing in very high winds

Extreme, but not acceptable situation and I can't start the work tomorrow morning

Calculate Levenshtein distance between two strings in Python

How can I plot a Farey diagram?

What is it called when one voice type sings a 'solo'?

Copycat chess is back

extract characters between two commas?

Lied on resume at previous job

How would photo IDs work for shapeshifters?



Is there a way to make member function NOT callable from constructor?


What are the differences between a pointer variable and a reference variable in C++?Can I call a constructor from another constructor (do constructor chaining) in C++?Throwing exceptions from constructorsHow do I call ::std::make_shared on a class with only protected or private constructors?Calling a base member in constructor in multiple inheritance in C++Equality-compare std::weak_ptrClass inheritance: Constructor and member functions of class not recognized by compilerHow does shared_ptr<T> detect that T derives from enable_shared_from_this<T>?enable_shared_from_this derived class methods are undefined referenceDefault move constructor with mutex member






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








16















I have member function (method) which uses



std::enable_shared_from_this::weak_from_this() 


In short: weak_from_this returns weak_ptr to this. One caveat is it can't be used from constructor.
If somebody would use my function from constructor of inherited class, weak_from_this inside it would return expired weak_ptr. I guard against that with assertion checking that it's not expired, but it's a run-time check.



Is there a way to check against it at compile time?










share|improve this question
























  • Note there is a difference in scope between a child class constructor body and the parent class constructor: the latter has been executed completely before you even start initializing the child class's members (if any), let alone enter the child class constructor body.

    – rubenvb
    15 hours ago






  • 3





    Nice question. One way would be to make a dummy class with pure virtual function weak_from_this and inherit yours from it. This will make it a hard compile error.

    – SergeyA
    15 hours ago






  • 3





    @SergeyA Why didn't you post that as an answer? All other people here seem to conclude that it's not possible so either your comment is wrong and misleading or they are wrong and you should show how it can be achieved.

    – Bakuriu
    9 hours ago

















16















I have member function (method) which uses



std::enable_shared_from_this::weak_from_this() 


In short: weak_from_this returns weak_ptr to this. One caveat is it can't be used from constructor.
If somebody would use my function from constructor of inherited class, weak_from_this inside it would return expired weak_ptr. I guard against that with assertion checking that it's not expired, but it's a run-time check.



Is there a way to check against it at compile time?










share|improve this question
























  • Note there is a difference in scope between a child class constructor body and the parent class constructor: the latter has been executed completely before you even start initializing the child class's members (if any), let alone enter the child class constructor body.

    – rubenvb
    15 hours ago






  • 3





    Nice question. One way would be to make a dummy class with pure virtual function weak_from_this and inherit yours from it. This will make it a hard compile error.

    – SergeyA
    15 hours ago






  • 3





    @SergeyA Why didn't you post that as an answer? All other people here seem to conclude that it's not possible so either your comment is wrong and misleading or they are wrong and you should show how it can be achieved.

    – Bakuriu
    9 hours ago













16












16








16


3






I have member function (method) which uses



std::enable_shared_from_this::weak_from_this() 


In short: weak_from_this returns weak_ptr to this. One caveat is it can't be used from constructor.
If somebody would use my function from constructor of inherited class, weak_from_this inside it would return expired weak_ptr. I guard against that with assertion checking that it's not expired, but it's a run-time check.



Is there a way to check against it at compile time?










share|improve this question
















I have member function (method) which uses



std::enable_shared_from_this::weak_from_this() 


In short: weak_from_this returns weak_ptr to this. One caveat is it can't be used from constructor.
If somebody would use my function from constructor of inherited class, weak_from_this inside it would return expired weak_ptr. I guard against that with assertion checking that it's not expired, but it's a run-time check.



Is there a way to check against it at compile time?







c++ c++17 shared-ptr weak-ptr






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 15 hours ago









armitus

524114




524114










asked 16 hours ago









KorriKorri

36129




36129












  • Note there is a difference in scope between a child class constructor body and the parent class constructor: the latter has been executed completely before you even start initializing the child class's members (if any), let alone enter the child class constructor body.

    – rubenvb
    15 hours ago






  • 3





    Nice question. One way would be to make a dummy class with pure virtual function weak_from_this and inherit yours from it. This will make it a hard compile error.

    – SergeyA
    15 hours ago






  • 3





    @SergeyA Why didn't you post that as an answer? All other people here seem to conclude that it's not possible so either your comment is wrong and misleading or they are wrong and you should show how it can be achieved.

    – Bakuriu
    9 hours ago

















  • Note there is a difference in scope between a child class constructor body and the parent class constructor: the latter has been executed completely before you even start initializing the child class's members (if any), let alone enter the child class constructor body.

    – rubenvb
    15 hours ago






  • 3





    Nice question. One way would be to make a dummy class with pure virtual function weak_from_this and inherit yours from it. This will make it a hard compile error.

    – SergeyA
    15 hours ago






  • 3





    @SergeyA Why didn't you post that as an answer? All other people here seem to conclude that it's not possible so either your comment is wrong and misleading or they are wrong and you should show how it can be achieved.

    – Bakuriu
    9 hours ago
















Note there is a difference in scope between a child class constructor body and the parent class constructor: the latter has been executed completely before you even start initializing the child class's members (if any), let alone enter the child class constructor body.

– rubenvb
15 hours ago





Note there is a difference in scope between a child class constructor body and the parent class constructor: the latter has been executed completely before you even start initializing the child class's members (if any), let alone enter the child class constructor body.

– rubenvb
15 hours ago




3




3





Nice question. One way would be to make a dummy class with pure virtual function weak_from_this and inherit yours from it. This will make it a hard compile error.

– SergeyA
15 hours ago





Nice question. One way would be to make a dummy class with pure virtual function weak_from_this and inherit yours from it. This will make it a hard compile error.

– SergeyA
15 hours ago




3




3





@SergeyA Why didn't you post that as an answer? All other people here seem to conclude that it's not possible so either your comment is wrong and misleading or they are wrong and you should show how it can be achieved.

– Bakuriu
9 hours ago





@SergeyA Why didn't you post that as an answer? All other people here seem to conclude that it's not possible so either your comment is wrong and misleading or they are wrong and you should show how it can be achieved.

– Bakuriu
9 hours ago












3 Answers
3






active

oldest

votes


















14














I am afraid the answer is "no, it's not possible to protect against this at compile-time." It's always difficult to prove a negative, but consider this: if it was possible to protect a function this way, it would probably have been done for weak_from_this and shared_from_this in the standard library itself.






share|improve this answer






























    4














    No there is no way. Consider:



    void call_me(struct widget*);

    struct widget : std::enable_shared_from_this<widget>
    widget()
    call_me(this);


    void display()
    shared_from_this();

    ;

    // later:

    void call_me(widget* w)
    w->display(); // crash



    The thing is there is a reason you want to check for not calling shared_from_this in the constructor. Think about that reason. It's not that shared_from_this cannot be called, it's because it's return value has no way of being assigned yet. It is also not because it will never be assigned. It's because it will be assigned later in the execution of the code. Order of operation is a runtime property of your program. You cannot assert at compile time for order of operation, which is done at runtime.






    share|improve this answer






























      4














      Not as such, but - if performance is not an issue, you could add a flag which indicates construction is complete, and use that to fail at run-time with such calls:



      class A 

      // ... whatever ...

      A()
      // do construction work
      constructed = true;


      foo()
      if (not constructed)
      throw std::logic_error("Cannot call foo() during construction");

      // the rest of foo


      bool constructed false ;



      You could also make these checks only apply when compiling in DEBUG mode (e.g. with conditional compilation using the preprocessor - #ifndef NDEBUG) so that at run time you won't get the performance penalty. Mind the noexcepts though.



      An alternative to throwing could be assert()'ing.






      share|improve this answer























      • Since apparently there isn't compile-time solution which doesn't make code less readable, I decided to go with assert(!wptr.expired()). I think it's a little bit more fitting than exception, because there is no way to recover from this situation.

        – Korri
        13 hours ago











      • @Korri remember that asserts are usually compiled out in release builds, so nothing will happen. An exception however is not, so it would still terminate the program (if not caught and swallowed) in a release build. You could do both; first assert then throw, or just throw.

        – Jesper Juhl
        12 hours ago












      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%2f55576192%2fis-there-a-way-to-make-member-function-not-callable-from-constructor%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









      14














      I am afraid the answer is "no, it's not possible to protect against this at compile-time." It's always difficult to prove a negative, but consider this: if it was possible to protect a function this way, it would probably have been done for weak_from_this and shared_from_this in the standard library itself.






      share|improve this answer



























        14














        I am afraid the answer is "no, it's not possible to protect against this at compile-time." It's always difficult to prove a negative, but consider this: if it was possible to protect a function this way, it would probably have been done for weak_from_this and shared_from_this in the standard library itself.






        share|improve this answer

























          14












          14








          14







          I am afraid the answer is "no, it's not possible to protect against this at compile-time." It's always difficult to prove a negative, but consider this: if it was possible to protect a function this way, it would probably have been done for weak_from_this and shared_from_this in the standard library itself.






          share|improve this answer













          I am afraid the answer is "no, it's not possible to protect against this at compile-time." It's always difficult to prove a negative, but consider this: if it was possible to protect a function this way, it would probably have been done for weak_from_this and shared_from_this in the standard library itself.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 15 hours ago









          AngewAngew

          135k11261354




          135k11261354























              4














              No there is no way. Consider:



              void call_me(struct widget*);

              struct widget : std::enable_shared_from_this<widget>
              widget()
              call_me(this);


              void display()
              shared_from_this();

              ;

              // later:

              void call_me(widget* w)
              w->display(); // crash



              The thing is there is a reason you want to check for not calling shared_from_this in the constructor. Think about that reason. It's not that shared_from_this cannot be called, it's because it's return value has no way of being assigned yet. It is also not because it will never be assigned. It's because it will be assigned later in the execution of the code. Order of operation is a runtime property of your program. You cannot assert at compile time for order of operation, which is done at runtime.






              share|improve this answer



























                4














                No there is no way. Consider:



                void call_me(struct widget*);

                struct widget : std::enable_shared_from_this<widget>
                widget()
                call_me(this);


                void display()
                shared_from_this();

                ;

                // later:

                void call_me(widget* w)
                w->display(); // crash



                The thing is there is a reason you want to check for not calling shared_from_this in the constructor. Think about that reason. It's not that shared_from_this cannot be called, it's because it's return value has no way of being assigned yet. It is also not because it will never be assigned. It's because it will be assigned later in the execution of the code. Order of operation is a runtime property of your program. You cannot assert at compile time for order of operation, which is done at runtime.






                share|improve this answer

























                  4












                  4








                  4







                  No there is no way. Consider:



                  void call_me(struct widget*);

                  struct widget : std::enable_shared_from_this<widget>
                  widget()
                  call_me(this);


                  void display()
                  shared_from_this();

                  ;

                  // later:

                  void call_me(widget* w)
                  w->display(); // crash



                  The thing is there is a reason you want to check for not calling shared_from_this in the constructor. Think about that reason. It's not that shared_from_this cannot be called, it's because it's return value has no way of being assigned yet. It is also not because it will never be assigned. It's because it will be assigned later in the execution of the code. Order of operation is a runtime property of your program. You cannot assert at compile time for order of operation, which is done at runtime.






                  share|improve this answer













                  No there is no way. Consider:



                  void call_me(struct widget*);

                  struct widget : std::enable_shared_from_this<widget>
                  widget()
                  call_me(this);


                  void display()
                  shared_from_this();

                  ;

                  // later:

                  void call_me(widget* w)
                  w->display(); // crash



                  The thing is there is a reason you want to check for not calling shared_from_this in the constructor. Think about that reason. It's not that shared_from_this cannot be called, it's because it's return value has no way of being assigned yet. It is also not because it will never be assigned. It's because it will be assigned later in the execution of the code. Order of operation is a runtime property of your program. You cannot assert at compile time for order of operation, which is done at runtime.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 15 hours ago









                  Guillaume RacicotGuillaume Racicot

                  16.3k53872




                  16.3k53872





















                      4














                      Not as such, but - if performance is not an issue, you could add a flag which indicates construction is complete, and use that to fail at run-time with such calls:



                      class A 

                      // ... whatever ...

                      A()
                      // do construction work
                      constructed = true;


                      foo()
                      if (not constructed)
                      throw std::logic_error("Cannot call foo() during construction");

                      // the rest of foo


                      bool constructed false ;



                      You could also make these checks only apply when compiling in DEBUG mode (e.g. with conditional compilation using the preprocessor - #ifndef NDEBUG) so that at run time you won't get the performance penalty. Mind the noexcepts though.



                      An alternative to throwing could be assert()'ing.






                      share|improve this answer























                      • Since apparently there isn't compile-time solution which doesn't make code less readable, I decided to go with assert(!wptr.expired()). I think it's a little bit more fitting than exception, because there is no way to recover from this situation.

                        – Korri
                        13 hours ago











                      • @Korri remember that asserts are usually compiled out in release builds, so nothing will happen. An exception however is not, so it would still terminate the program (if not caught and swallowed) in a release build. You could do both; first assert then throw, or just throw.

                        – Jesper Juhl
                        12 hours ago
















                      4














                      Not as such, but - if performance is not an issue, you could add a flag which indicates construction is complete, and use that to fail at run-time with such calls:



                      class A 

                      // ... whatever ...

                      A()
                      // do construction work
                      constructed = true;


                      foo()
                      if (not constructed)
                      throw std::logic_error("Cannot call foo() during construction");

                      // the rest of foo


                      bool constructed false ;



                      You could also make these checks only apply when compiling in DEBUG mode (e.g. with conditional compilation using the preprocessor - #ifndef NDEBUG) so that at run time you won't get the performance penalty. Mind the noexcepts though.



                      An alternative to throwing could be assert()'ing.






                      share|improve this answer























                      • Since apparently there isn't compile-time solution which doesn't make code less readable, I decided to go with assert(!wptr.expired()). I think it's a little bit more fitting than exception, because there is no way to recover from this situation.

                        – Korri
                        13 hours ago











                      • @Korri remember that asserts are usually compiled out in release builds, so nothing will happen. An exception however is not, so it would still terminate the program (if not caught and swallowed) in a release build. You could do both; first assert then throw, or just throw.

                        – Jesper Juhl
                        12 hours ago














                      4












                      4








                      4







                      Not as such, but - if performance is not an issue, you could add a flag which indicates construction is complete, and use that to fail at run-time with such calls:



                      class A 

                      // ... whatever ...

                      A()
                      // do construction work
                      constructed = true;


                      foo()
                      if (not constructed)
                      throw std::logic_error("Cannot call foo() during construction");

                      // the rest of foo


                      bool constructed false ;



                      You could also make these checks only apply when compiling in DEBUG mode (e.g. with conditional compilation using the preprocessor - #ifndef NDEBUG) so that at run time you won't get the performance penalty. Mind the noexcepts though.



                      An alternative to throwing could be assert()'ing.






                      share|improve this answer













                      Not as such, but - if performance is not an issue, you could add a flag which indicates construction is complete, and use that to fail at run-time with such calls:



                      class A 

                      // ... whatever ...

                      A()
                      // do construction work
                      constructed = true;


                      foo()
                      if (not constructed)
                      throw std::logic_error("Cannot call foo() during construction");

                      // the rest of foo


                      bool constructed false ;



                      You could also make these checks only apply when compiling in DEBUG mode (e.g. with conditional compilation using the preprocessor - #ifndef NDEBUG) so that at run time you won't get the performance penalty. Mind the noexcepts though.



                      An alternative to throwing could be assert()'ing.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 13 hours ago









                      einpoklumeinpoklum

                      37k28132263




                      37k28132263












                      • Since apparently there isn't compile-time solution which doesn't make code less readable, I decided to go with assert(!wptr.expired()). I think it's a little bit more fitting than exception, because there is no way to recover from this situation.

                        – Korri
                        13 hours ago











                      • @Korri remember that asserts are usually compiled out in release builds, so nothing will happen. An exception however is not, so it would still terminate the program (if not caught and swallowed) in a release build. You could do both; first assert then throw, or just throw.

                        – Jesper Juhl
                        12 hours ago


















                      • Since apparently there isn't compile-time solution which doesn't make code less readable, I decided to go with assert(!wptr.expired()). I think it's a little bit more fitting than exception, because there is no way to recover from this situation.

                        – Korri
                        13 hours ago











                      • @Korri remember that asserts are usually compiled out in release builds, so nothing will happen. An exception however is not, so it would still terminate the program (if not caught and swallowed) in a release build. You could do both; first assert then throw, or just throw.

                        – Jesper Juhl
                        12 hours ago

















                      Since apparently there isn't compile-time solution which doesn't make code less readable, I decided to go with assert(!wptr.expired()). I think it's a little bit more fitting than exception, because there is no way to recover from this situation.

                      – Korri
                      13 hours ago





                      Since apparently there isn't compile-time solution which doesn't make code less readable, I decided to go with assert(!wptr.expired()). I think it's a little bit more fitting than exception, because there is no way to recover from this situation.

                      – Korri
                      13 hours ago













                      @Korri remember that asserts are usually compiled out in release builds, so nothing will happen. An exception however is not, so it would still terminate the program (if not caught and swallowed) in a release build. You could do both; first assert then throw, or just throw.

                      – Jesper Juhl
                      12 hours ago






                      @Korri remember that asserts are usually compiled out in release builds, so nothing will happen. An exception however is not, so it would still terminate the program (if not caught and swallowed) in a release build. You could do both; first assert then throw, or just throw.

                      – Jesper Juhl
                      12 hours ago


















                      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%2f55576192%2fis-there-a-way-to-make-member-function-not-callable-from-constructor%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

                      Magento 2 duplicate PHPSESSID cookie when using session_start() in custom php scriptMagento 2: User cant logged in into to account page, no error showing!Magento duplicate on subdomainGrabbing storeview from cookie (after using language selector)How do I run php custom script on magento2Magento 2: Include PHP script in headerSession lock after using Cm_RedisSessionscript php to update stockMagento set cookie popupMagento 2 session id cookie - where to find it?How to import Configurable product from csv with custom attributes using php scriptMagento 2 run custom PHP script

                      Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

                      How to solve knockout JS error in Magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2