Exercise 12-5 in Accelerated C++.

My operator+= works:

void Str2::operator+=(const Str2& a)
{
	iterator new_data = alloc.allocate((avail - data) + a.size());
	iterator new_avail = std::uninitialized_copy(data, avail, new_data);
	new_avail = std::uninitialized_copy(a.data, a.avail, new_avail);

	uncreate();

	data = new_data;
	limit = avail = new_avail;
}

However i cant get the operator+ to work:(

Str2 operator+(const Str2& a, const Str2& b)
{
	Str2 r = a;
	r += b; 
	return r;
}

Error: Debug Assertion Failed!
Expression: _BLOC_TYPE_IS_VALID(pHead->nBlockUse)

Its probably something obvious.
Any help is appreciated!!

> My operator+= works
> However i cant get the operator+ to work

The problem seems to be in your copy constructor; operator+ needs to make a copy.

First, verify that the copy constructor Str2::Str2( const Str2& ) is working correctly.

How can your += operator work?! It doesn't return anything. The declaration should be:

Str2 & Str2::operator+=(const Str2& a);

and in the implementation you should return *this. Same for the + operator.
You can read about operator overlading here.

How can your += operator work?! It doesn't return anything.

I can only use += after a Str2. I do the work on that Str2 object so i dont have to return anything. I dont know if its better or worse, but it works :P

The problem seems to be in your copy constructor; operator+ needs to make a copy.

I had forgot to make a copy constructor, + works fine now, thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.