+ Reply to Thread
Results 1 to 2 of 2

Thread: Why copy constructor calls while I insert an element in vector?

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    46

    Why copy constructor calls while I insert an element in vector?

    Why copy constructor gets called while I insert an element in vector?

    Code:

    Code:
    class CStudent
    {
    private:
    	char m_szName[10] ;
    public:
    	CStudent(char szName[10])
    	{
    		 strcpy(m_szName, szName) ;
    	}
    
    	CStudent(const CStudent& objStudent)
    	{
    		strcpy(m_szName, objStudent.m_szName) ;
    	}
    } ;
    
    void InsertElement()
    {
            std::vector<CStudent> myVector ;
    
    	CStudent objStudent("Rose") ;
    
    	myVector.push_back(objStudent) ; //copy constructor gets called... why?
    }
    How can I avoid this?

    Help.

  2. #2
    This is because when you call push_back it creates a temporary object and copies it to vector.

    To avoid this, you can use:

    Code:
    std::vector<CStudent*> myVector ;
    
    CStudent* pStudent = new CStudent("Rose") ;
    
    myVector.push_back(pStudent) ;
    Here you pass the pointer rather than whole object!

    Note:
    You will need to delete the object from vector when you are done.

+ 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