Reputation: 1615
why isn't it common place to use boost::optional as a scoped_ptr, it seems like it is better as the object is created on the stack instead of the heap. But I have never seen it used this way. My question is, what are the disadvantages of using a boost::optional as a kind of scoped_ptr other than the obvious inability to do polymorphism?
Upvotes: 1
Views: 402
Reputation: 15814
The reason is that polymorphism is the point of scoped_ptr
. Otherwise you would just declare the variable locally, on stack.
int main()
{
Class object(52, 25); //sample declaration, with constructor arguments passed
}
EDIT 1 (response to additional info from comments):
boost::scoped_ptr
is actually rarely used for the purpose you describe (mainly because you can't copy nor move boost::scoped_ptr
, making the class you store it in uncopyable and unmoveable). It seems that boost::optional
is appropriate for that purpose, but...
Note that there is little point in local use of boost::optional
(that is, not returned from a function), since you can create objects on stack at your will:
void another_function()
{
if(some_condition())
{
Class object(0, 0); // create the object
// use the object
}
else
{
// don't use the object
}
}
Upvotes: 3
Reputation: 1178
For one, I'd say semantics.
I would need to refresh my memory on boost::optional
and boost::scoped_ptr
details to give an opinion on the technical aspect, but when it comes to maintainability, using optional
s in place of pointers is bound to confuse people who read your code.
Upvotes: 2