I have a lot of C # code that I have to write in C ++. I have little experience in C ++.
I am using Visual Studio 2012 to build. The project is a Static Library in C ++ (not in C ++ / CLI).
I have a class with a static method with a static private member. When I debug, I see both the Constructor creator and the Copy Constructor invoked. I do not understand why both are called, I thought that only one would be. Is there a way I can force to call only one constructor?
This is my code.
MyClass& MyClass::MyInstance() { static MyClass myLocalVariable = MyClass(); return myLocalVariable ; }
When calling the MyInstance method:
- MyClass constructor is first called
- Then CopyConstructor
- And then the line "return myInstance".
Is it possible that the instance stored by myLocalVariable is only temporary and can be destroyed later?
Update:
Since some people cannot reproduce my problem, I am adding more code here. I have 3 projects with the same behavior (one of them is a static library, which I call from my Unit tests, and the other 2 are Win32 Console Applications)
C ++ Main
int _tmain(int argc, _TCHAR* argv[]) { MyClass& instance = MyClass::MyInstance(); return 0; }
C ++ MyClass.h
#pragma once #include <string> using namespace std; class MyClass { private: string name; public: MyClass(void); MyClass(string name); MyClass(const MyClass&); ~MyClass(void); static MyClass& MyInstance(); };
C ++ MyClass.cpp
#include "MyClass.h" #include <iostream> using std::cout; MyClass::MyClass(void) { cout << "Empty Cons\n"; } MyClass::MyClass(string name) { this->name = name; cout << "Parameters Cons\n"; } MyClass::MyClass(const MyClass& myClass) { name = myClass.name; cout << "Copy Cons\n"; } MyClass::~MyClass(void) { cout << "Destructor\n"; } MyClass& MyClass::MyInstance() { cout << "MyInstance\n"; static MyClass myInstance = MyClass("MyClassName"); return myInstance; }
My conclusion:
Myinstance
Minus options
Copy cons
destructor
c ++ visual-studio-2012
Dzyann
source share