In article <ops5acq3cgmmfhfz@max>, Maett <no@spam.pls> wrote:
Hi all,
I have my own string class with a reference counted body.
By mistake I wrote
mystring str = str = "abcde";
Did I invoke undefined behavior ?
(I guess so since I got a segfault)
Here my problem with some similar example code:
///////////////////////
#include <boost/shared_ptr.hpp>
int main()
{
boost::shared_ptr<double> f(new double);
boost::shared_ptr<double> g = g = f; // --- UB ?
return 0;
}
///////////////////////
Remember, assignment is from right to left, so first g = f is called (on
an uninitialized g, *then* the copy c_tor is called to create g.
If your op= uses the temp-swap trick, it will seg fault every time (if
your lucky.)
This should make it clear what is happening:
class foo {
static int c;
int i;
public:
foo(): i( c++ ) { cout << "default c_tor " << i << '\n'; }
foo( const foo& ): i( c++ ) { cout << "copy c_tor " << i << '\n'; }
~foo() { cout << "d_tor " << i << '\n'; }
foo& operator=( const foo& o ) {
cout << "op= from " << i << " to " << o.i << '\n';
}
};
int foo::c = 0;
int main() {
foo w;
foo i = i = w;
}
On my machine, I got:
default c_tor 0
op= from -1880846991 to 0
copy c_tor 1
d_tor 1
d_tor 0
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.