我有一个程序,它创建了大量的对象并将它们插入到一个向量中.我的想法是创建大约10,000个对象,但我发现该程序在几千个之后崩溃了.在崩溃之前创建的对象数量是随机的,取决于我是否修改了代码中的任何行,所以我认为是一个与内存分配有关的问题.
我正在创建的对象是这样的:
class Object {
public:
//Needed by map
Object() {
}
Object(int newID, std::string newText) {
id = newID;
text = newText;
}
int getID() {
return id;
}
std::string getText() {
return text;
}
~Object() {
}
private:
int id;
std::string text;
};
Run Code Online (Sandbox Code Playgroud)
没有什么特别的,正如你所看到的.创建对象的程序如下:
int main(int argc, char** argv) {
int numberOfElements;
long start;
long end;
long time1, time2, time3, time4, time5, time6;
numberOfElements = 7000; //7000<X<7050 Maximum reliable
{
//Measuring time for creation of 1000 elements in …Run Code Online (Sandbox Code Playgroud) 我一直在面对这个警告.
我有一个主要的C++程序,它创建了几个线程.这些线程运行特定类中的函数.为了做到这一点,这个类有一个静态函数,它返回我用来在这些线程中运行的实际函数.我会粘贴代码的相关部分,以便您更好地理解它.
这些是Car.h的相关部分,它的函数在线程中运行的类的标题:
[...]
class Car {
public:
[...]
void *GoForward(void); //Runs in the thread
static void* GoForward_helper(void *); //Sends the previous one to the thread
[...]
Run Code Online (Sandbox Code Playgroud)
这是Car.cpp中传递给pthread_create作为参数的函数,它返回真正在线程中运行的函数.这是我发现在一个线程中运行不同类的函数的唯一方法:
[...]
void *Car::GoForward_helper(void *context) {
//Just getting parameters, not big deal
ThreadParameters* parameters = (ThreadParameters*) context;
int newSlot = parameters->GetSlot();
parameters->GetCar()->setSlot(newSlot);
//Returns the function I want to run in the thread
return parameters->GetCar()->GoForward();
}
[...]
void* Car::GoForward(void) {
//Tasks which actually run in the thread
}
[...]
Run Code Online (Sandbox Code Playgroud)
这些是发送给辅助函数的参数.没有什么相关的,我为了方便您粘贴它们:
[...]
class ThreadParameters { …Run Code Online (Sandbox Code Playgroud)