+ Reply to Thread
Results 1 to 2 of 2

Thread: Using move asignment operator in C++

  1. #1

    Using move asignment operator in C++

    I want to learn move asignment operator and its usage. Can anybody let me know how to use it in C++? Can I use this feature in VS 2005? Please help.

  2. #2
    Moe assignemnt operator is like overloading = operator with "&&" (r-value reference).

    No, you will need to use VS 2010 or later version of Visual Studio.

    Example:

    Code:
    class CMyObject
    {
    private:
    	int m_nDataLength ;
    	unsigned char* m_pdata ;
    public:
    	CMyObject()
    	{
    		m_pdata = nullptr ;
    		m_nDataLength = 0 ;
    	}
    
    	CMyObject(int nDataLength, unsigned char *pdata)
    	{
    		if (NULL != pdata)
    		{
    			m_pdata = new unsigned char[nDataLength] ;
    			memcpy(m_pdata, pdata, nDataLength) ;
    			m_nDataLength = nDataLength ;
    		}
    	}
    		
    	CMyObject& operator=(CMyObject&& objMyObject)
    	{
    		if (this != &objMyObject)
    		{
    			delete [] m_pdata ;
    			m_pdata = nullptr ;
    			m_nDataLength = 0 ;
    
    			if (NULL != objMyObject.m_pdata)
    			{
    				m_pdata = new unsigned char[objMyObject.m_nDataLength] ;
    				memcpy(m_pdata, objMyObject.m_pdata, objMyObject.m_nDataLength) ;
    				m_nDataLength = objMyObject.m_nDataLength ;
    
    				objMyObject.m_pdata = nullptr ;
    				objMyObject.m_nDataLength = 0 ;
    			}
    		}
    
    		return *this ;
    	}
    	
    	~CMyObject()
    	{
    		if (NULL != m_pdata)
    		{
    			delete []m_pdata ;
    			m_pdata = nullptr ;
    		}
    		m_nDataLength = 0 ;
    	}
    } ;
    
    CMyObject ReturnAnObject()
    {
    	return CMyObject(strlen("hello world 1"), (unsigned char *)"hello world 1") ;
    }
    
    void CMyDlg::OnBnClickedOk()
    {
    	CMyObject objMyObject1 ;
    	objMyObject1 = ReturnAnObject() ;
    }

+ Reply to Thread

Tags for this 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