CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2010
    Posts
    907

    Returning a smart pointer by value?

    Seems like the newly created pointer is destroyed after returning to the caller.
    The values are trashed.
    Is this the correct way to retrieve a smart pointer.
    I do have a copy constructor for cPoint for PathPoint.
    Thanks
    Jack

    Code:
    boost::shared_ptr<cPoint> CPF_SimObject::nextWayPoint()
    {
    	pathIndex++;
    	if (pathIndex < m_cpf_path.size()-1) {
    		PathPoint location = m_cpf_path.at(pathIndex);		 		
    		
    		return boost::shared_ptr<cPoint>(new cPoint(location));
    		  
    	}
    	return boost::shared_ptr<cPoint>(new cPoint(GetPos()));	 
    }

  2. #2
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Returning a smart pointer by value?

    This is the correct way to do it. Your pointer indeed gets trashed, but that's OK, since you are also returning a copy, so your reference count does not drop to 0 (unless your compiler implements [N]RVO, in which case the local pointer is created onto the return value).

    Also, use make_shared. It's more convenient, and has better exception safety guarantees:
    Code:
    boost::shared_ptr<cPoint> CPF_SimObject::nextWayPoint()
    {
    	pathIndex++;
    	if (pathIndex < m_cpf_path.size()-1) {
    		PathPoint location = m_cpf_path.at(pathIndex);		 		
    		return boost::make_shared<cPoint>(location);
    	}
    	return boost::make_shared_ptr<cPoint>(GetPos());	 
    }
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  3. #3
    Join Date
    Dec 2010
    Posts
    907

    Re: Returning a smart pointer by value?

    Sorry monarch,
    It is indeed correct, there are some other bugs in other spots of my program.
    Fixed that already.
    Thanks a lot
    Jack

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured