我正在尝试理解C++内存管理。据我所知,堆栈上的对象只保证在当前代码块中存活(如果堆栈没有溢出)。如果我从此代码块调用函数并将堆栈对象的链接传递给该函数,则必须工作,因为调用块仍然存在。
如果我从当前代码块启动新线程,堆栈对象会发生什么情况?据我所知,该块被认为已完成。
问题在于,堆栈变量在块完成后还会存在一段时间,因此我无法确定它们是否得以存活。
这里有一些代码。它可以编译并正常工作,但我认为不能保证它可以工作。
main.h:
我的问题是:
如果我从当前代码块启动新线程,堆栈对象会发生什么情况?据我所知,该块被认为已完成。
问题在于,堆栈变量在块完成后还会存在一段时间,因此我无法确定它们是否得以存活。
这里有一些代码。它可以编译并正常工作,但我认为不能保证它可以工作。
main.h:
#include <QObject>
#include <QThread>
#ifndef MAIN_H
#define MAIN_H
class MyThread : public QThread
{
Q_OBJECT
virtual void run();
signals:
void returnVar(int *aPtr, int *bPtr);
public:
int *a;
int *b;
};
class MyClass : public QObject
{
Q_OBJECT
int a; // Is it considered stack or global?
void someFunc(int *aPtr, int *bPtr);
MyThread thread; // Is it OK to create thread objects like this or should I use heap only?
public:
MyClass();
public slots:
void varAdded(int *aPtr, int *bPtr);
};
#endif // MAIN_H
.cpp 文件:
#include <QCoreApplication>
#include <QDebug>
#include "main.h"
void MyThread::run()
{
qDebug() << "A in thread: " << *a << ", B in thread: " << *b;
emit returnVar(a, b);
}
MyClass::MyClass()
{
a = 1;
int b = 2;
someFunc(&a, &b);
//MyThread thread; // If i declare thread here program will crush because thread was destroyed while running
QObject::connect(&thread, SIGNAL(returnVar(int*, int*)), this, SLOT(varAdded(int*, int*)));
thread.a = &a;
thread.b = &b;
// Is current block considered alive when I start a thread?
// As far as I understand it it not alive any more. Am I right?
thread.start();
// If I give this block some time I can create stack thread object in constructor and it will work
//std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
void MyClass::someFunc(int *aPtr, int *bPtr)
{
// As far as I understand these objects will work fine anyway because calling block is alive.
// Am I right?
qDebug() << "A: " << *aPtr << ", B: " << *bPtr;
}
void MyClass::varAdded(int *aPtr, int *bPtr)
{
qDebug() << "A returned from thread: " << *aPtr << ", B returned from thread: " << *bPtr;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClass myClass;
return a.exec();
}
我的问题是:
- a和thread是堆栈或全局对象吗?
- 声明线程对象的方式是否正确,或者应该只在堆中创建它们?
- a和b对象保证在线程中存在吗?
- a和b对象在从线程返回(它们的引用)时保证存在吗?
main
中定义的堆栈对象在程序运行期间一直存在。 - user2100815