我无法在托管类中初始化静态本机指针。
以下是详细信息:我创建了一个C ++ / CLI控制台项目,并在其中声明了一个静态非托管指针。但是我无法用任何方法初始化静态指针(但是如果我将指针放入匿名命名空间,那么就没有问题,在代码中进行了演示)。你遇到过类似情况并找到解决办法吗?
代码在这里:
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();
}
答案 0 :(得分:2)
我发现(使用VS2005)调试器确认你所说的内容 - 指针的值在更新时不会改变。但是如果你输出一些东西,代码实际上是有效的。
我相信这是调试器中的错误。
答案 1 :(得分:0)
我没有看到代码有任何问题,它对我来说很好。不需要匿名命名空间。
#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();
}