0

I expected that GetStudent() function returns unique instance of Student. As I expected, that function returns unique instance of Student Class. I double checked the memory address returned by GetStudent() function. But very strange thing was that Student's constructor called every time when I called GetSutent() function. The code like below. The programming enviroment was VC6.0 & MFC project.

   //someApp.h
    Student& GetStudent();


    //someApp.cpp
    Student& GetStudent()
    {
       static Student _student;
       return _student;
    }


    //client1Class.cpp
    #include "someApp.h"
    void CCliend1Class::DoSomething()
    {
      GetStudent().DoSomething();
    }



    //client2Class.cpp
    #include "someApp.h"
    void CClient2Class::DoSomething()
    {
      GetStudent().DoSomething();
    }
5
  • Are you sure you are not creating another Student somewhere in DoSomething()? Commented Dec 30, 2011 at 0:39
  • Add code how have you checked pointer to returned Student object, I suspect that some temporary object caused constructor to be called multiple times. Commented Dec 30, 2011 at 0:40
  • luskan // int adrr = &GetSudent() Commented Dec 30, 2011 at 0:50
  • 1
    You might have a better experience with one of this century's compilers. Commented Dec 30, 2011 at 1:19
  • 1
    Please post minimal, compilable code that demonstrates the problem. If, in fact, the constructor for Student is being called each time GetStudent() is called, there's some important detail missing from the code you posted (even if you're using a compiler as old as VC6). Commented Dec 30, 2011 at 2:03

1 Answer 1

1

The object in GetStudent() should only be constructed the first time the function is called (assuming there is no contention between different threads calling that function; I'm not sure what happens in the threaded case but this isn't the question). There should indeed be only one object returned from this function throughout the application.

BTW, this isn't about "file scope static function" but about "function scope static variables".

Sign up to request clarification or add additional context in comments.

1 Comment

I wonder if how that works in multithread enviroment cause GetStudent() was called between different threads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.