+ Reply to Thread
Results 1 to 2 of 2

Thread: What is mutable keyword in C++?

  1. #1

    What is mutable keyword in C++?

    Hi All,

    What is mutable keyword in C++?

    Regards.

  2. #2
    Hi,

    'mutable' data member can be modified from 'const' member function of a class!

    Code:
    class CMutable
    {
    private:
    	mutable CRITICAL_SECTION m_objCriticalSection ;
    
    	int m_nValue ;
    
    public:
    	CMutable(int nValue)
    	{
    		InitializeCriticalSection(&m_objCriticalSection) ;
    		m_nValue = nValue ;
    	}
    
    	~CMutable()
    	{
    		DeleteCriticalSection(&m_objCriticalSection) ;
    	}
    
    	int GetValue() const
    	{
    		EnterCriticalSection(&m_objCriticalSection) ;
    		int nValue = m_nValue ;
    		LeaveCriticalSection(&m_objCriticalSection) ;
    		return nValue ;
    	}
    } ;
    
    void UseMutable()
    {
    	CMutable objMutable(42) ;
    
    	//Without mutable keyword in CRITICAL_SECTION m_objCriticalSection definition, code will not compile!
    	//But we need to enter into the critical section so that code can still be thread safe.
    	//So make CRITICAL_SECTION m_objCriticalSection mutable.
    	int nValue = objMutable.GetValue() ;
    }
    Regards.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts