I have a lot of C# Code that I have to write in C++. I don't have much experience in C++.
I am using Visual Studio 2012 to build. The project is an 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 can see both the Constructor and the Copy Constructor being called. I don't understand why both get called, I thought only one would. Is there a way that I could make only one constructor get called?
This is my code
MyClass& MyClass::MyInstance()
{
static MyClass myLocalVariable = MyClass(/*parameters*/);
return myLocalVariable ;
}
When the Method MyInstance gets called:
- First the Constructor of MyClass is called
- Then the CopyConstructor
- And then the "return myInstance" line.
Is it possible that the instance being held by myLocalVariable is only temporal and could get destroyed later on?
Update:
Since some people can not reproduce my problem, I am adding here more code. I have now 3 projects with the same behavior (one is a static library I am calling 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 Output:
Myinstance
Parameters Cons
Copy Cons
Destructor