mardi 6 avril 2021

conflicting declaration std::lock_guard

I don't understand why the following code returns an error.

#include <mutex>

int main() {
    std::mutex mtx;
    std::lock_guard<std::mutex> (mtx);
}

lock.cpp: In function ‘int main()’:

lock.cpp:5:37: error: conflicting declaration ‘std::lock_guardstd::mutex mtx’ std::lock_guardstd::mutex (mtx);

lock.cpp:4:16: note: previous declaration as ‘std::mutex mtx’ std::mutex mtx;

But, the following code compiles correctly.

class Test {
public:
    void lock() {
        std::lock_guard<std::mutex> (this->mtx_);
        std::lock_guard<std::mutex> (this->mtx_);
    }

private:
    std::mutex mtx_;
};

But, the following code is not ok.

int main() {
    std::lock_guard<std::mutex> (mtx);
    std::lock_guard<std::mutex> (mtx);
}

Aucun commentaire:

Enregistrer un commentaire