2013-10-09 91 views
0

我嘗試實現基於升壓互斥鎖宏,代碼如下:錯誤:預期不合格-ID,而使用升壓互斥

#include <boost/thread.hpp> 
#include <iostream> 

using namespace std; 

#define lock(x) if(Lock _lock_=x){}else 

class Mutex{ 
public: 
    friend class Lock; 

private: 
    boost::mutex mutex_; 

    void Lock(){ 
     mutex_.lock(); 
    }; 

    void Unlock(){ 
     mutex_.unlock(); 
    }; 
}; 

class Lock{ 
public: 
    Lock(Mutex& mutex):mutex_(mutex){mutex_.Lock();}; 
    ~Lock(){mutex_.Unlock();}; 

    operator bool() const { 
     return false; 
    } 

private: 
    Mutex& mutex_; 
}; 

void wait(int seconds) 
{ 
    boost::this_thread::sleep(boost::posix_time::seconds(seconds)); 
} 

void thread() 
{ 
    Mutex mtx; 
    for (int i = 0; i < 5; ++i) 
    { 
     lock(mtx){ 
      wait(1); 
      std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; 
     } 
    } 
} 

int main() 
{ 
    boost::thread t1(thread); 
    boost::thread t2(thread); 
    t1.join(); 
    t2.join(); 
} 

當我在Mac OS使用clang++ -std=c++11 -stdlib=libc++ lock_raii.cc -lboost_system -lboost_thread編譯。有錯誤信息:

lock_raii.cc:16:10: error: expected unqualified-id 
       mutex_.lock(); 
        ^
lock_raii.cc:6:17: note: expanded from macro 'lock' 
#define lock(x) if(Lock _lock_=x){}else 
       ^
1 error generated. 

那麼,它有什麼問題呢?

+1

錯誤信息說明問題;您有一個與此成員函數名稱相同的預處理器宏。因此,它被擴展的宏取代,這不是你想要的。出於這個原因,不要使用全部小寫字母來命名宏(更喜歡全部大寫)。 –

+1

是不是因爲你對mutex_.lock()的調用被你的宏「攔截」了? – 2013-10-09 20:35:04

回答

2

這裏是mutex_.lock();看起來像宏展開後:

mutex_.if(Lock _lock_=){}else; 
相關問題