Как вызвать конструктор с объявлением unique_ptr и обработать сигнал завершения программы - PullRequest
3 голосов
/ 01 апреля 2019

Я создал класс с конструктором.

Я создаю n число объектов в main.cpp. Теперь при каждом создании объекта конструктор должен вызываться автоматически.

Но так как я создаю этот объект в 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] (новый сеанс (count));

Есть предложения?

1 Ответ

1 голос
/ 01 апреля 2019

Вам не нужно удалять unique_ptr, они будут уничтожены, когда переменная выйдет из области видимости; в этом случае это будет конец основной функции.

В этом суть 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...