-
April 5th, 2016, 08:39 AM
#1
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()));
}
-
April 5th, 2016, 12:11 PM
#2
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.
-
April 6th, 2016, 01:06 AM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|