a piece of code for handle - body

T

Tony Johansson

Hello!

Here I have an Handle body example and reference-counted String Class Copy
constructor and Destructor.
The class definition is called String and StringRep se below.
This class definitions below is taken from a course I was on for some time
again.
I have added this code
String()
{ myBody = new StringRep(); } which is the String constructor

Why is not the copy constructor for class StringRep called in this statement
myBody(s.myBody) that I have in the copy constructor for class String.

Can somebody explain what this code does.?

class String
{
private:
StringRep* myBody;
public:
String()
{ myBody = new StringRep(); }

String(const String& s) : myBody(s.myBody)
{ myBody -> refCount++; }

~String()
{
if (--myBody->refCount == 0)
delete myBody;
}
....
....
};

class StringRep
{
private:
char* myChars;
int refCount;
StringRep(const StringRep& sr) : refCount(1)
{
//now copy the chars
......
}
friend class String;
};

//Tony
 
K

Kai-Uwe Bux

Tony said:
Hello!

[snip]
Why is not the copy constructor for class StringRep called in this
statement myBody(s.myBody) that I have in the copy constructor for class
String.

It isn't. What is called is the copy constructor for the type StringRep*.
Can somebody explain what this code does.?

class String
{
private:
StringRep* myBody;
public:
String()
{ myBody = new StringRep(); }

String(const String& s) : myBody(s.myBody)
{ myBody -> refCount++; }

Note that s.myBody is of type StringRep*. The newly created String object
has its own pointer to the StringRep object that presumably represents the
string and keeps track of the reference count. This pointer is initialized
from the pointer in the String object s.


Best

Kai-Uwe Bux

PS. a) What's wrong with std::string?

PS. b) Your code is not thread safe, e.g., you cannot asume that
incrementing the reference count is atomic.
 
J

Jonathan Mcdougall

Here I have an Handle body example and
reference-counted String Class Copy
constructor and Destructor.
The class definition is called String
and StringRep se below.
This class definitions below is taken
from a course I was on for some time
again. I have added this code
String() { myBody = new StringRep(); }
which is the String constructor
Why is not the copy constructor for
class StringRep called in this
statement
myBody(s.myBody)

Because this is copying a pointer, not the object.
that I have in the copy constructor
for class String.
Can somebody explain what this code
does.?

<snip>

Have a look at Scott Meyer's "More Effective C++", Item 29.


Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top