Reputation: 1820
Why doesn't this work?
struct O {
O(int i, int j)
: i(i)
, j(j)
{}
int const i;
int const j;
};
int main(int argc, char** argv)
{
boost::optional<O> i;
i.reset(O(4, 5));
return 0;
}
It seems to be trying to use the assignment operator instead of trying to construct it in place. I had assumed it would call the copy constructor of O on uninitialized memory.
/..../include/boost/optional/optional.hpp:433:69: error: use of deleted function ‘O& O::operator=(const O&)’
.... error: ‘O& O::operator=(const O&)’ is implicitly deleted because the default definition would be ill-formed:
.... error: non-static const member ‘const int O::i’, can’t use default assignment operator
.... error: non-static const member ‘const int O::j’, can’t use default assignment operator
Upvotes: 2
Views: 1215
Reputation: 15768
Boost.Optional uses either assignment or copy-construction, depending on the state of i
. As this state is run-time information, the choice between assignment and copy-construction also has to be made at run-time.
This means, however, that the compiler has to generate code for both options, even if one of them is never actually used. And that means that both options must be possible.
To get the code working, you could add an (always failing) assingment operator to class O
:
O& O::operator=(const O&)
{
throw "this is not possible"
return *this;
}
As a side note, Optional<T>::reset
is deprecated. You should just use assingment, as in
i = O(4,5);
The above described semantics are valid for both.
Upvotes: 2