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?
-
2What's wrong with just declaring the variable you want, why wrap it in boost::optional?– Cheers and hth. - AlfMar 25, 2014 at 13:45
-
I had the same thoughts. From a performance point of view boost::optional would beat scoped_ptr. Only serious drawback is the semantics (or lack of polymorphism as 'milleniumbug' points out)– gast128Aug 14, 2017 at 9:13
2 Answers
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
}
}
-
2There is another purpose which is to have a member that can be created and destroyed independently of the class that it is a member of. Maybe a lazy initialised object?– danMar 25, 2014 at 13:54
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 optionals in place of pointers is bound to confuse people who read your code.
-
It would help if boost / std would define something like e.g. value_ptr with the same implementation as boost::optional.– gast128Aug 14, 2017 at 9:14