Reputation: 97
I'm not able to initialize a static native pointer inside a managed class.
Here's the detail: I created a C++/CLI console project and declared a static unmanaged pointer inside. However I can't initialize the static pointer with any means (but if I put the pointer into an anonymous namespace, there's no problem, demoed in the code). Did u meet similar situations and got solutions for it?
Code here:
class MyTask
{
public:
int m_index;
MyTask()
{
m_index = 0;
}
};
namespace
{
static MyTask* s_pTask;
}
public ref class MyApplication
{
public:
static MyTask* sm_pTask;
static void InitizlizeStaticMembers(MyTask* pTask)
{
sm_pTask = pTask;
}
void AddTask()
{
sm_pTask = new MyTask();
}
};
void main()
{
MyApplication^ app = gcnew MyApplication();
// 1st, doesn't work (sm_pTask is still null after the execution)
MyApplication::sm_pTask = new MyTask();
// 2nd, doesn't work (pTask can be initialized correctly, sm_pTask is still null after the execution)
MyTask* pTask = new MyTask();
MyApplication::InitizlizeStaticMembers(pTask);
// 3rd, doesn't work (sm_pTask is still null after the execution)
app->AddTask();
// 4th, work(s_pTask can be initialized correctly)
s_pTask = new MyTask();
}
Upvotes: 2
Views: 2306
Reputation: 4186
I found that (with VS2005) the debugger confirms what you said - the value of the pointer doesn't change as it gets updated. But the code is actually working if you make it output something.
I believe this is a bug in the debugger.
Upvotes: 2
Reputation: 27184
I don't see any issue with the code and it works fine for me. The anonymous namespace is not needed.
#include "stdafx.h"
#include <iostream>
class MyTask
{
public:
int m_index;
MyTask()
{
m_index = 0;
}
};
static MyTask* s_pTask;
public ref class MyApplication
{
public:
static MyTask* sm_pTask = NULL;
static void InitizlizeStaticMembers(MyTask* pTask)
{
sm_pTask = pTask;
}
void AddTask()
{
sm_pTask = new MyTask();
}
};
void main()
{
MyApplication^ app = gcnew MyApplication();
// 1st, doesn't work (sm_pTask is still null after the execution)
std::cout << "MyApplication::sm_pTask before new " << MyApplication::sm_pTask << '\n'; // 0
MyApplication::sm_pTask = new MyTask();
std::cout << "MyApplication::sm_pTask after new " << MyApplication::sm_pTask << '\n'; // 003B8170
MyTask* pTask = new MyTask();
std::cout << "pTask= " << pTask << '\n'; // 003B81A0
MyApplication::InitizlizeStaticMembers(pTask);
std::cout << "MyApplication::sm_pTask = " << MyApplication::sm_pTask << '\n'; // 003B81A0
app->AddTask();
s_pTask = new MyTask();
}
Upvotes: 0