The const char * operator overwrites (?) My other variable in a weird way

#include <iostream> #include <sstream> class Vector { double _x; double _y; public: Vector(double x, double y) : _x(x), _y(y) {} double getX() { return _x; } double getY() { return _y; } operator const char*() { std::ostringstream os; os << "Vector(" << getX() << "," << getY() << ")"; return os.str().c_str(); } }; int main() { Vector w1(1.1,2.2); Vector w2(3.3,4.4); std::cout << "Vector w1(" << w1.getX() << ","<< w1.getY() << ")"<< std::endl; std::cout << "Vector w2(" << w2.getX() << ","<< w2.getY() << ")"<< std::endl; const char* n1 = w1; const char* n2 = w2; std::cout << n1 << std::endl; std::cout << n2 << std::endl; } 

The output of this program:

 $ ./a.out Vector w1(1.1,2.2) Vector w2(3.3,4.4) Vector(3.3,4.4) Vector(3.3,4.4) 

I do not understand why I get the conclusion. It seems that "const char * n2 = w2;" overwrites n1 and then I get Vector twice (3.3.4.4). "Can someone explain these phenomena to me?

+6
source share
1 answer

This undefined behavior, which sometimes works (good luck), sometimes does not.

You are returning a pointer to a temporary local object. A pointer to a temporary local object is the inside of the string object obtained by calling os.str().c_str() .

If you want to easily print these objects with cout , you can overload the << operator for output streams. How:

 ostream& operator<<(ostream& out, const Vector &a) { std::ostringstream os; os << "Vector(" << a.getX() << "," << a.getY() << ")"; out << os.str(); return out; } 

and then

 std::cout << w1 << std::endl; std::cout << w2 << std::endl; 
+13
source

Source: https://habr.com/ru/post/958392/


All Articles