+ Reply to Thread
Results 1 to 2 of 2

Thread: can I use shared_ptr with STL container classes?

  1. #1

    can I use shared_ptr with STL container classes?

    I want to use shared_ptr with STL container classes. Can I use shared_ptr with STL class like map, set or vector? If yes, please let me know how to use it? Thanks!

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Yes, you can use shared_pr with STL objects.

    Example:
    Code:
    class CValue
    {
    private:
    	int m_nValue ;
    public:
    	CValue(int nValue)
    	{
    		OutputDebugString("Constructor called!\n") ;
    		m_nValue = nValue ;
    	}
    
    	~CValue()
    	{
    		OutputDebugString("Destructor called!\n") ;
    	}
    
    	int GetValue()
    	{
    		return m_nValue ;
    	}
    } ;
    
    void SharedPtrWithSTLContainer()
    {
    	std::vector<std::shared_ptr<CValue>> vecValues ;
    
    	vecValues.push_back(std::make_shared<CValue>(10)) ;
    	vecValues.push_back(std::make_shared<CValue>(20)) ;
    	vecValues.push_back(std::make_shared<CValue>(30)) ;
    
    	std::vector<std::shared_ptr<CValue>>::const_iterator itr = vecValues.begin() ;
    	for (; itr != vecValues.end() ; itr++)
    	{
    		int nValue = itr->get()->GetValue() ; 
    		char szMessage[100] ; 
    		sprintf(szMessage, "Object Value = %d\n", nValue) ;
    		OutputDebugString(szMessage) ;
    	}
    
    	vecValues.erase(vecValues.begin(), vecValues.end()) ;
    }

+ 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