【问题标题】:How to call a constructor with unique_ptr declaration and handle the program termination signal如何使用 unique_ptr 声明调用构造函数并处理程序终止信号
【发布时间】:2019-08-22 07:58:33
【问题描述】:

我创建了一个带有构造函数的类。

我正在 main.cpp 中创建 n 个 个对象。现在每次创建对象时,都应该自动调用构造函数。

但是由于我是在main.cpp 中创建这个对象,所以我想使用信号来处理“Ctrl+C”终止。

我已经这样写了main.cpp

#include <iostream>
#include "Session.hpp"

class Session {
public:
    Session(int _count):count(_count) {
        std::cout << "Create Session " << count << std::endl;
    }
    ~Session() {
        std::cout << "Destroy Session " << count << std::endl;
    }
    Print() {
        cout << "Hello" << endl;
    }
private:
    const int count;
};

void signal_handler(int signal, unsigned int count, **WHAT SHOULD I WRITE HERE**) {
    for (unsigned int del_count = 0; del_count < count; del_count++) {
        **I WANT TO DELETE ALL THE FOO OBJECTS CREATED IN THE MAIN FUNCTION**
    }
}

int main() {
    unsigned int num_of_sessions;
    cin >> num_of_sessions;

    signal(SIGINT, signal_handler, num_of_sessions, **WHAT MORE SHOULD I PASS HERE**);

    unique_ptr<Session> Foo[num_of_sessions];
    unsigned int count = 0; // initialize the counter for sessions

    while (count < num_of_sessions) {
        Foo[count] (new Session(count));
        count++;
    }
    while (true){
        for (count = 0; count < num_of_sessions; count++) {
            Foo[count]->PrintName();
        }
    }
    return 0;
}

我收到此错误

错误:对“(std::unique_ptr) (Session*)”的调用不匹配
Foo[count] (new Session(count));

有什么建议吗?

【问题讨论】:

  • 是的。 Foo[count].reset(new Session(count));
  • 在您的信号处理函数中,您可以设置一个标志,供您的无限循环检查。如果设置则循环中断,main 函数结束,这将破坏Foo 数组中的所有对象,这将删除指针并破坏Session 对象。
  • 至于您的构建错误,这与信号处理程序问题非常不同,应该作为一个单独的问题提出,这不是您构建 any 对象的方式。
  • @Someprogrammerdude you could set a flag that your infinite loop checks 你能推荐任何实现这个的例子吗?
  • std::atomic&lt;bool&gt; end_infinite_loop = false; void signal_handler(int) { end_infinite_loop = true; } ... int main() { ... while (!end_infinite_loop) { ... } }

标签: c++ class oop constructor unique-ptr


【解决方案1】:

你不需要删除unique_ptr,它们会在变量超出范围时被销毁;在这种情况下,它将是 main 函数的结尾。

这就是 unique_ptr 的意义所在,您不必关心内存管理。

如果您只是想设置一个信号并对分配在主函数内部堆栈中的对象执行操作,您可以使用这样的指针:

#include <iostream>
#include <csignal>
#include <vector>
#include <atomic>
#include <memory>
#include <chrono>
#include <thread>

std::atomic<bool> end_condition;
class Session {
    public:
    Session(int _count):count(_count) {
        std::cout << "Create Session " << count << std::endl;
    }
    ~Session() {
        std::cout << "Destroy Session " << count << std::endl;
    }
    void printSessionCount() {
        std::cout << "Session count is " << count << std::endl;
    }
    private:
    const int count;
};
std::vector< std::unique_ptr<Session>>* foo_p; // <= Probably not necessary but this is how you would access your variable defined in main in signal handler

void signal_handler(int signal) {
   // You don't have handle clean up of your vector.
   // foo_p->clear(); <= Unnecessary to delete every element of your vector here, since they will be automatically deleted at the end of main
    end_condition.store(false);
}

int main() {
    end_condition.store(true);
    unsigned int num_of_sessions;
    std::cin >> num_of_sessions;

    // register signal SIGINT and signal handler
    signal(SIGINT, signal_handler);

    std::vector< std::unique_ptr<Session> > foo;
    foo_p = &foo; // Make your global pointer points to your pointer created in the main function. Accessing foo_p before the point will result in a segmentation fault since the pointer will be null
   // You may not need this at all depending on what you want to do during in the signal handler

    for(int i = 0; i < num_of_sessions; ++i) {
        // Populate your vector
        foo.emplace_back(new Session(i));
    }

    while (end_condition.load()){
        //Call a function for each vector
        for(int i =0; i < foo.size(); ++i) {
            foo.at(i)->printSessionCount();
        }
         std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    return 0;
}    // vector foo memory will be deleted here

【讨论】:

  • 嘿Clonk 感谢您的回答。我对向量不是很好。你能告诉我如何使用向量中的每个对象来调用 Session 类的函数吗?请参阅编辑以供参考
  • 我编辑了答案以在 while 循环中调用函数。我还添加了您的 while 循环的临时化以避免循环太快(也是使用 std::chrono 和 std::thread 的示例)
  • 请注意,您应该使用std::vector而不是c-array,它更安全,您可以动态更改大小。
猜你喜欢
  • 1970-01-01
  • 2013-07-26
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
相关资源
最近更新 更多