What would be a “Hello, World!” example for “std::ref”?

后端 未结 4 2117
星月不相逢
星月不相逢 2021-01-30 01:54

Can somebody give a simple example which demonstrates the functionality of std::ref? I mean an example in which some other constructs (like tuples, or data type tem

4条回答
  •  忘掉有多难
    2021-01-30 02:56

    // Producer Consumer Problem

    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    class Buffer {
    
        std::mutex m;
        std::condition_variable cv;
        std::deque queue;
        const unsigned long size = 1000;
    
        public:
        void addNum(int num) {
            std::unique_lock lock(m);
            cv.wait(lock, [this]() { return queue.size() <= size; });
            queue.push_back(num);
            cout << "Pushed " << num << endl;
            lock.unlock();
            cv.notify_all();
        }
        int removeNum() {
            std::unique_lock lock(m);
            cv.wait(lock, [this]() { return queue.size()>0; });
            int num = queue.back();
            queue.pop_back();
            cout << "Poped " << num << endl;
            lock.unlock();
            cv.notify_all();
            return num;
        }
    
    };
    
    void producer(int val, Buffer& buf) {
        for(int i=0; i

    Just another use of std::ref in main while passing Buffer object as reference in producer and consumer. If std::ref not used then this code will not compile.

提交回复
热议问题