I want to convert my type back and forth between string representation and actual data using boost::lexical_cast
. This is what I'm trying to do:
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <string>
struct Foo
{
Foo() = default;
Foo(const std::string& str)
: str(str)
{
}
friend std::istream& operator>>(std::istream& is, Foo& foo);
friend std::ostream& operator<<(std::ostream& os, const Foo& foo);
private:
std::string str;
};
// For conversion to Foo.
std::istream& operator>>(std::istream& is, Foo& foo)
{
return is >> foo.str;
}
// For conversion from Foo.
std::ostream& operator<<(std::ostream& os, const Foo& foo)
{
return os << foo.str;
}
int main()
{
boost::lexical_cast<Foo>("ok");
boost::lexical_cast<std::string>(Foo("ok"));
}
But this results in a segfault. Why?
It sounds like the crash is due to a stack overflow. I think your operator>>
is calling itself, by implicitly converting foo.str
back into a Foo
.
Try removing the implicit conversion by making that constructor explicit:
explicit Foo(const std::string& str) noexcept
: str(str)
{
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments