I cannot use move semantics introduced in C++11, so to emulate move semantics I occasionally use scoped_ptr and use swap explicitly to show ownership changes.
I've ran into an issue in which I don't know how to do this with the contained boost::variant types. For simplicity sake take this naive example:
#include <boost/scoped_ptr.hpp>
#include <boost/variant.hpp>
#include <string>
#include <vector>
typedef boost::variant<
boost::scoped_ptr<std::string>,
boost::scoped_ptr<std::vector<std::string> > vType;
int main(int argc, char **argv) {
boost::scoped_ptr<std::vector<std::string> > vec = new std::vector;
vType var;
// How do I assign vec to var to hand off ownership and prevent
// recreation of the vector?
// ??
return 0;
}
Is there anything like a boost::swap(boost::variant, value::type)
overload or alternative that would assign the variant value using swap on the value type internal to the variant? That would be the ideal solution.
Things I have already considered:
I could use a shared_ptr to prevent copies, but I rather use scoped_ptr to enforce single ownership and remove the overhead of shared_ptr.
std::auto_ptr would give me the semantics I'd like but it is also easy to mistakenly make assignments and switch ownership. So far this seems like my best option, but I was intentionally staying away from it for the reason stated.
I could create a wrapper class or template for the string and vector which is used in the variant that has a copy assignment operator which internally does move like semantics, but then I might as well be using std::auto_ptr.
I could create a union (like) class instead of using boost::variant, but I wanted to take advantage of some of the tools available to me in boost with dealing with the variant type.
So any other suggestions, or good arguments for the options I did enumerated?
UPDATE
This question is similar: boost::variant; std::unique_ptr and copy
Even though the conclusion in that question is that a non-copyable type can't be used with boost variant, I still need to solve my general usecase: Move semantics when assigning my types to a boost::variant without the availability of C++11 rvalue semantics.