C++ 可拆卸线程完成操作时取消分配内存

C++ 可拆卸线程完成操作时取消分配内存,c++,boost,C++,Boost,下面是我们使用的示例 class CustomThread { public: CustomThread(const std::wstring &id1) { t = new test(id1); } ~CustomThread(); void startThread() { std::cout << "Do threading Operation here....." <<

下面是我们使用的示例

class CustomThread
{
public:
    CustomThread(const std::wstring &id1)
    {
         t = new test(id1);
    }
    ~CustomThread();        

    void startThread() {
        std::cout << "Do threading Operation here....." << std::endl;
    }

private:
    std::wstring id;
    test *t;
};


int main()
{
    for (int i = 1; i < 100; i++)
    {
        std::wstring id = L"1";
        CustomThread *ct = new CustomThread(id);

        boost::thread new_thread;
        new_thread = boost::thread(& CustomThread::startThread, ct);
        new_thread.detach();        
    }

    // sleep for 100 second - to complete the thread task....
    sleep(100);
    return 0;

}
class自定义线程
{
公众:
自定义线程(const std::wstring&id1)
{
t=新试验(id1);
}
~CustomThread();
void startThread(){

std::cout这里有两个问题。首先,由于
CustomThread
获取了一个它需要遵循的资源

现在,让我们看看你的设计。你动态地分配一个
CustomThread
,这样它就不会在for循环结束时被破坏,并且会一直持续到线程的生命周期。这里的问题是你不知道什么时候删除这个类,即使你删除了,你仍然没有指针来调用delete你可能会存储这些指针,但你仍有可能在线程完成之前删除对象。我们需要做的是以某种方式将线程和对象耦合在一起,这样我们就知道对象在线程完成运行后被销毁。我们可以使用帮助器函数来完成此操作。如果我们有

void thread_runner(std::wstring param)
{
    CustomThread ct(param);
    ct.startThread();
}
然后我们可以在循环中调用这个函数

for (int i = 1; i < 100; i++)
{
    std::wstring id = L"1"; 
    boost::thread new_thread;
    new_thread = boost::thread(&thread_runner, id);
    new_thread.detach();        
}
for(int i=1;i<100;i++)
{
std::wstring id=L“1”;
boost::线程新线程;
新线程=boost::线程(&thread\u runner,id);
新螺纹。分离();
}

现在,
CustomThread
对象被自动清理,您不必担心何时何地调用
delete
(假设您的类具有正确的析构函数,或者您切换到RAII指针类型)如果调用了<代码>新的<代码>,你必须调用<代码>删除>代码>。C++中内存管理的诀窍就是永远不要使用<代码>新的<代码>。你是否可以在整个地方使用指针?如果你的类不可复制,那么就更喜欢值语义。它可能仍然是可移动的。不要分离线程。猜猜它们需要多长时间才能完成(这是对
睡眠(100)
的调用),加入它们。问题是为什么需要创建100个线程并将它们全部分离。也许这不是最好的设计和“测试”应该在CustomThread的析构函数中或在startThread方法的and处销毁。析构函数的目的是释放对象可能获得的资源。因此,它通常是放置删除的合适位置。鉴于到目前为止的代码示例,析构函数肯定位于我放置删除测试的位置。new it I在构造函数中,在析构函数中删除它。