MyClass *myInstance = new MyClass[1];
// myInstance is a pointer variable which contains
// an address. It points to a memory location at which
// we have an array of ONE MyClass.
MyClass *tempList = new MyClass[myCount+1];
// creates a NEW allocation, without touching the original.
// tempList is now also a pointer variable. It contains
// an address, the address of a different memory location
// at which we now have 2 myClass instances. This is
// NOT the same location.
tempList[0] = myInstance[0];
// the MyClass instances at *myInstance and *tempList
// are now copies of each other, but only the first instances.
myInstance=tempList;
// myInstance is now pointing to tempList, but the array
// of MyClass instances that it pointed to are still
// allocated. Unfortunately, you no-longer have the
// address stored in any variables. This is called a leak.
您应该考虑查看其中一个 STL 容器,例如std::vector或std::list。如果您需要使用动态分配,请考虑使用 std::vector。见std::unique_ptr。
编辑:
你在评论中说你正在打电话
EziSocialObject::sharedObject()->setFacebookDelegate(this);
这将使用您调用它的特定实例的地址调用 setFacebookDelegate 。您还说它作为单例运行,但您正在分配它的多个实例。
MyClass* a = new MyClass;
MyClass* b = new MyClass; // No-longer a singleton.
EziSocialObject::sharedObject()->setFacebookDelegate(a);
// From this point on, a->fbUserPhotoCallback will be called.
对代码的初步浏览表明它可能是线程化的——它有一个管理系统来处理多个、潜在的并发或重叠请求,我当然不希望每次 facebook 响应刷新请求缓慢时我的游戏都会停止.
我仍然不清楚你为什么需要向量——你似乎将所有数据都存储在其他地方,而你实际上只需要一个向量条目,它的唯一功能似乎是从其他类获取数据和使其可用于“MyClass”,但似乎您应该能够通过桥接或查找类来做到这一点,例如 astd::map<std::string /*FaceBookID*/, size_t localID>
或std::map<std::string /*FaceBookID*/, RealClass*>
.
您可以尝试以下方法:
// enable asserts -- only affects debug build.
#include <assert.h>
// Add a counter to track when we clear the vector,
// and track what the count was last time we called getFacebookPhoto
size_t g_vectorClears = 0;
static const size_t VECTOR_NOT_IN_USE = ~0;
size_t g_vectorUsed = VECTOR_NOT_IN_USE;
// When we clear the vector, check if we are using it.
assert(g_vectorUsed == VECTOR_NOT_IN_USE);
++g_vectorClears;
g_myInstances.clear();
// When you call getFacebookPhoto, store which clear we were on
g_vectorUsed = g_vectorClears;
blah->getFacebookPhoto(...);
// In MyClass->fbUserPhotoCallback, validate:
...
fbUserPhotoCallback(...)
{
assert(g_vectorUsed == g_vectorClears);
...
// at the end, set g_vectorUsed back to NOT_IN_USE.
g_vectorUsed = VECTOR_NOT_IN_USE;
}
如果插件没有线程化,那么剩下的可能性是你在某个地方传递了向量的地址或向量的数据并且你正在破坏它,或者插件有内存泄漏导致它踩到你的向量。
为了进一步提供帮助,您需要包含更多代码。