Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. scope in functions

scope in functions

Scheduled Pinned Locked Moved C / C++ / MFC
question
21 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M minkowski

    Hi If I have the function int * foo() { int x = 6; int * ptr = &x; return ptr; } I was wondering how this works because the local variable x is destroyed upon leaving the function so doesn'nt the pointer ptr be invalid? Also, is the copy constructor called in returning ptr? And is ptr destroyed upon leaving the function since that goes out of scope too? Thanks for any answers.

    B Offline
    B Offline
    BadKarma
    wrote on last edited by
    #8

    Let me explain what happens. int x = 6; creates a int variable on the stack and sets it to the value 6 int * ptr = &x; creates a pointer to integer variable on the stack and sets the value to the stack address where x is located. return ptr; retuns to the calling function lowering the stack pointer to where it was before calling the function. and returns the value of the pointer. The pointer is now addressing somewhere in the unused stack space. The values of the stack remain there until the are overwritten/needed for other variables, or other function calls. In other words this is not a good practice and should never be used. I don't know what you mean about the copy constructor, since int isn't a class so it doesn't have a copy constructor in the way you think.

    codito ergo sum

    M 1 Reply Last reply
    0
    • C CPallini

      Well, there is only a big mistake: you're are returning a pointer to a temporary value, this you must never do, because calling code cannot consider reliable the pointer. :)

      If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

      M Offline
      M Offline
      minkowski
      wrote on last edited by
      #9

      Hi CPallini, Yes I agree with that and I was wondering why it still works. How is the pointer returned? Is it copied with a copy constructor? Thanks.

      T C 2 Replies Last reply
      0
      • M minkowski

        Hi ya, But I thought that x goes out of scope which means it is released. So since ptr is pointing to x then that is not valid. However, I know this works (having tried it) so the reasoning seems to be although that x goes out of scope, the memory has not been yet over written so it works. Is that right? And is a copy constructor called in returning the pointer? Thanks.

        T Offline
        T Offline
        toxcct
        wrote on last edited by
        #10

        actually, x went out of scope, so the variable x is destroyed, but even if is x doesn't exist anymore, what you get with the pointer is the address at which x was stored... so, yes, the memory occupied by x is released (so that any other memory request could use this space), but not overwritten, that means that the value persists until some write a new variable's value on it. you musn't do the asumption that immediately when exiting your function, the caller can get the value pointed by x though


        [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

        1 Reply Last reply
        0
        • M minkowski

          Hi CPallini, Yes I agree with that and I was wondering why it still works. How is the pointer returned? Is it copied with a copy constructor? Thanks.

          T Offline
          T Offline
          toxcct
          wrote on last edited by
          #11

          the address is returned by value... but why would you wind about this ?


          [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

          1 Reply Last reply
          0
          • B BadKarma

            Let me explain what happens. int x = 6; creates a int variable on the stack and sets it to the value 6 int * ptr = &x; creates a pointer to integer variable on the stack and sets the value to the stack address where x is located. return ptr; retuns to the calling function lowering the stack pointer to where it was before calling the function. and returns the value of the pointer. The pointer is now addressing somewhere in the unused stack space. The values of the stack remain there until the are overwritten/needed for other variables, or other function calls. In other words this is not a good practice and should never be used. I don't know what you mean about the copy constructor, since int isn't a class so it doesn't have a copy constructor in the way you think.

            codito ergo sum

            M Offline
            M Offline
            minkowski
            wrote on last edited by
            #12

            Hi BadKarma Thanks for that. Yes I thought it was bad practice to return an object on the stack in a function call. With regards to the copy constructor, if I have a class alpha in the function alpha * func() { alpha anything; alpha *ptr = &anything; return ptr; } how would it return ptr. Would it copy the pointer ptr using the copy constructor and then destroy it as the function goes out of scope? Thanks.

            T J 2 Replies Last reply
            0
            • M minkowski

              Hi BadKarma Thanks for that. Yes I thought it was bad practice to return an object on the stack in a function call. With regards to the copy constructor, if I have a class alpha in the function alpha * func() { alpha anything; alpha *ptr = &anything; return ptr; } how would it return ptr. Would it copy the pointer ptr using the copy constructor and then destroy it as the function goes out of scope? Thanks.

              T Offline
              T Offline
              toxcct
              wrote on last edited by
              #13

              you're doing the exactly same mistake... your object "anything", whether it's an int or an alpha, is local to the function, so destroyed when getting out of space...


              [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

              M 1 Reply Last reply
              0
              • T toxcct

                you're doing the exactly same mistake... your object "anything", whether it's an int or an alpha, is local to the function, so destroyed when getting out of space...


                [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

                M Offline
                M Offline
                minkowski
                wrote on last edited by
                #14

                Hi ya I know about the mistake of the object on the stack going out of scope. I was questioning how it returns the pointer. It just copies the address and does not involve using copy constructors? Is that right ? Thanks.

                T C 2 Replies Last reply
                0
                • M minkowski

                  Hi ya I know about the mistake of the object on the stack going out of scope. I was questioning how it returns the pointer. It just copies the address and does not involve using copy constructors? Is that right ? Thanks.

                  T Offline
                  T Offline
                  toxcct
                  wrote on last edited by
                  #15

                  you're confusing about the object life, and the returning stuff. there's no copy constructors (actually, not even basic constructors at all) for pointers...


                  [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

                  1 Reply Last reply
                  0
                  • M minkowski

                    Hi ya I know about the mistake of the object on the stack going out of scope. I was questioning how it returns the pointer. It just copies the address and does not involve using copy constructors? Is that right ? Thanks.

                    C Offline
                    C Offline
                    Cedric Moonen
                    wrote on last edited by
                    #16

                    minkowski wrote:

                    It just copies the address and does not involve using copy constructors?

                    Yes, no copy constructor are involved. In fact, no constructor at all will be called, because you don't construct a new object. You only delete an object (when the function goes out of scope) and then return its address. Which is of course very very bad :).


                    Cédric Moonen Software developer
                    Charting control [v1.2 - Updated]

                    M 1 Reply Last reply
                    0
                    • C Cedric Moonen

                      minkowski wrote:

                      It just copies the address and does not involve using copy constructors?

                      Yes, no copy constructor are involved. In fact, no constructor at all will be called, because you don't construct a new object. You only delete an object (when the function goes out of scope) and then return its address. Which is of course very very bad :).


                      Cédric Moonen Software developer
                      Charting control [v1.2 - Updated]

                      M Offline
                      M Offline
                      minkowski
                      wrote on last edited by
                      #17

                      Ok thanks! :-D

                      1 Reply Last reply
                      0
                      • M minkowski

                        Hi CPallini, Yes I agree with that and I was wondering why it still works. How is the pointer returned? Is it copied with a copy constructor? Thanks.

                        C Offline
                        C Offline
                        CPallini
                        wrote on last edited by
                        #18

                        As toxcct pointed out, it's returned by value. :)

                        If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                        T 1 Reply Last reply
                        0
                        • M minkowski

                          Hi BadKarma Thanks for that. Yes I thought it was bad practice to return an object on the stack in a function call. With regards to the copy constructor, if I have a class alpha in the function alpha * func() { alpha anything; alpha *ptr = &anything; return ptr; } how would it return ptr. Would it copy the pointer ptr using the copy constructor and then destroy it as the function goes out of scope? Thanks.

                          J Offline
                          J Offline
                          jhwurmbach
                          wrote on last edited by
                          #19

                          minkowski wrote:

                          alpha * func()
                          {
                          alpha anything;
                          alpha *ptr = &anything;
                          return ptr;

                          }

                          how would it return ptr. Would it copy the pointer ptr using the copy constructor and then destroy it as the function goes out of scope?

                          The type you return is pointer. In this case, pointer to alpha. And pointers do not have such things as copy constructors. So, no copy c'tor is called.


                          Failure is not an option - it's built right in.

                          1 Reply Last reply
                          0
                          • C CPallini

                            As toxcct pointed out, it's returned by value. :)

                            If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                            T Offline
                            T Offline
                            toxcct
                            wrote on last edited by
                            #20

                            and as an idiot is roaming over here, all my posts today got voted 1 or 2 :suss:


                            [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

                            C 1 Reply Last reply
                            0
                            • T toxcct

                              and as an idiot is roaming over here, all my posts today got voted 1 or 2 :suss:


                              [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

                              C Offline
                              C Offline
                              CPallini
                              wrote on last edited by
                              #21

                              Simply don't worry about. Helping people it's more rewarding than getting high scores; unfortunately, idiots can be found everywhere, even here. :)

                              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups