473,383 Members | 1,846 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

std:string assignments


Hello,

For many years ago I implemented my own string buffer class, which
works fine except assignments - it copies the char* buffer instead of
the pointer. Therefore in function calls I pass "const char*" and get
the result in a parameter by reference "MyString& result".

I'd like to move to nicer strings. In order to keep platform/compiler
independence I consider std:string as the replacement. While googling
I managed to read some warnings about std:string not being thread safe
(any shared memory is not without a lock, is it?). I wonder about
assignment - does it copy the buffer or the pointer? I managed to find
only one document which explicitly warned about
"implementation-specific issues" where any reference to the memory
makes the buffer unique. Any other problems on moderns compilers?

I checked the following assignment on Borland C++ Builder:

string s1 = "abc";
string s2 = s1;
cerr << (int)s1.c_str() << ‘ ‘ << (int)s2.c_str();

s1.c_str() and s2.c_str() show different addresses. I wonder whether
the assignment or c_str() copied the buffer.

If I return a string from a function, would it return a pointer or
would copy the buffer (copy constructor).

Should I abandon my own string buffer at all knowing it works?

Thank you for any advice,
Erik
May 23 '06 #1
6 5644
Erik wrote:
I'd like to move to nicer strings. In order to keep platform/compiler
independence I consider std:string as the replacement. While googling
I managed to read some warnings about std:string not being thread safe
AFAIK, none of standard classes are. C++ has no concept of 'thread'.
As to any particular implementation, you would have to ask in another
newsgroup, the one dedicated to that implementation.
(any shared memory is not without a lock, is it?). I wonder about
assignment - does it copy the buffer or the pointer?
Unknown. Implemenation-specific.
I managed to find
only one document which explicitly warned about
"implementation-specific issues" where any reference to the memory
makes the buffer unique. Any other problems on moderns compilers?
Plenty. What exactly are you interested in?
I checked the following assignment on Borland C++ Builder:

string s1 = "abc";
string s2 = s1;
cerr << (int)s1.c_str() << ' ' << (int)s2.c_str();

s1.c_str() and s2.c_str() show different addresses. I wonder whether
the assignment or c_str() copied the buffer.
Ask in 'borland.public.cppbuilder.language'.
If I return a string from a function, would it return a pointer or
would copy the buffer (copy constructor).
It would return an object. The object would be a temporary created
using copy semantics (copy-constructed).
Should I abandon my own string buffer at all knowing it works?


Use what works.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 23 '06 #2
"Erik" <er***@dsv.su.se> wrote in message
news:fa********************************@4ax.com...
string s1 = "abc";
string s2 = s1;


string is a class

string s1; // declare a variable of typle class string

internally in the string class there are the base string, some char array
and such.
now that we have s1 as a string we can work with it.

s1 = "text";

s1 is now equal to "text"

if we declare another string..

string s2;

and do like you do in your sample

s2 = s1;

In the string class there is operator= defined, and it will copy the content
of s1 into s2.
Not only the pointer, but the whole string. If it only copied the pointer to
the string object this would be a problem:

string s1,s2,s2;
s1 = "Hello",
s2 += "World!";
s3 = s1;
s3 += " ";
s3 += s2;
cout << s3 << endl;

prints "Hello World!";

string is not thread safe. Like any other class where 2 or more threads
share the same object.
If this is the case when you use the string.. you can just make you own
class derived from std::string and add a simple lock.
However i dont see the need for multiply threads to manipulate the same
string.

Anyway 2 threads can not write to same block of memory at the same time.
if you only have 1 cpu the OS will time slice between each thread and
therefore can only 1 thread write memory.
However, lets say you assign a value to a string in thread 1, while
std::string is copying and is only 50% done
the os decides that this threads timeslice ended, and now thread 2 will be
given time. If thread 2 also writes to
this same string, then you would end up with a "mixed" content.. eg. thread
1 puts "text" into the string and thread 2 puts "abcd" into it.
the result might look like "aesd". With 2 or more processors, the value in
memory cant be written by 2 processors at the same time.
However, in the example before the os would time slice, with 2 processors
the 2 threads might run simultaniously.
In that case the bytes written in memory, will have the value written from
the last cpu that flushes it memory cache
(it will overwrite whats written before by the other cpu).

however, there is no worries if many threads just read the variable and none
of them writes to it.

I hope that was understandable..

//eric
May 23 '06 #3
"Erik" <er***@dsv.su.se> wrote in message
news:fa********************************@4ax.com...

Hello,

For many years ago I implemented my own string buffer class, which
works fine except assignments - it copies the char* buffer instead of
the pointer. Therefore in function calls I pass "const char*" and get
the result in a parameter by reference "MyString& result".

I'd like to move to nicer strings. In order to keep platform/compiler
independence I consider std:string as the replacement. While googling
I managed to read some warnings about std:string not being thread safe
(any shared memory is not without a lock, is it?).
Correct, if you want to make it thread safe you will need to wrap it in a
thread safe class with your own locking mechanisms. On a side note, if you
do this you probably won't have to write locking for every string function,
only the ones you'll be using, although that can be a bit.
I wonder about
assignment - does it copy the buffer or the pointer?
Buffer.
I managed to find
only one document which explicitly warned about
"implementation-specific issues" where any reference to the memory
makes the buffer unique.
I'm not sure what you mean here, are you talking about .c_str()? And yes,
the memory .c_str() points too only remains until the string has changed.
I'm not sure if it becomes invalidated at that point or not. It's best to
only use .c_str() for short lived operations (copy it to a buffer, output
it, etc...)
Any other problems on moderns compilers?
It depends on what you consider a problem I guess.
I checked the following assignment on Borland C++ Builder:

string s1 = "abc";
string s2 = s1;
cerr << (int)s1.c_str() << ' ' << (int)s2.c_str();

s1.c_str() and s2.c_str() show different addresses. I wonder whether
the assignment or c_str() copied the buffer.
Yes, it would copy the buffer. Two different strings are unique and contain
their own pointer to their own memory for storage of the data. s2 has it's
own data pointer which gets allocated with enough memory to hold the string
"abc" (and maybe some more) then the data gets copied into this buffer.
If I return a string from a function, would it return a pointer or
would copy the buffer (copy constructor).
Usually it would copy the buffer but the compiler may optimize this away if
you're real lucky.
Should I abandon my own string buffer at all knowing it works?


It depends on how different std::string is for you and if you can get it to
work. If it does 90% excactly the same as your string class, I would
probably switch to std::string and deal with the differences. If they are
only 50% compatable I would take a closer look.
May 23 '06 #4
Erik wrote:
Hello,

For many years ago I implemented my own string buffer class, which
works fine except assignments - it copies the char* buffer instead of
the pointer. Therefore in function calls I pass "const char*" and get
the result in a parameter by reference "MyString& result".

I'd like to move to nicer strings. In order to keep platform/compiler
independence I consider std:string as the replacement. While googling
I managed to read some warnings about std:string not being thread safe
(any shared memory is not without a lock, is it?). I wonder about
assignment - does it copy the buffer or the pointer? I managed to find
only one document which explicitly warned about
"implementation-specific issues" where any reference to the memory
makes the buffer unique. Any other problems on moderns compilers?

I checked the following assignment on Borland C++ Builder:

string s1 = "abc";
string s2 = s1;
cerr << (int)s1.c_str() << ‘ ‘ << (int)s2.c_str();

s1.c_str() and s2.c_str() show different addresses. I wonder whether
the assignment or c_str() copied the buffer.

If I return a string from a function, would it return a pointer or
would copy the buffer (copy constructor).

Should I abandon my own string buffer at all knowing it works?

Thank you for any advice,
Erik

Before you answer that question, you might want to stop and consider the
situations in which you are using strings. It may turn out that our
concern about copying strings is ill-founded. If you are -- for
instance -- generating dynamic content for some CGI script, and you are
throwing literally millions of strings around per second, which could be
kilobytes in length, then it is reasonable to worry about the time and
memory spent copying a string.

If, however, you are using strings to handle a few details in your
program -- for instance, parsing some user input, formating some output
and error messages -- it's probably safe to say that the time and memory
spent copying strings needlessly is insignificant.

The amount of time you spend worrying about string should be
proportional to the amount of time your computer does. If your computer
is spending a huge amount of time managing large numbers of long
strings, you might want to consider implementing a specialized string
class, with copy-on-write and all sorts of other goodies. If, however,
your computer is only spending a tiny amount of time working with
strings, be content to use std::string, and damn the 15 nanoseconds
spend needlessly copying them.
Jack Saalweachter
May 23 '06 #5
Erik wrote :
For many years ago I implemented my own string buffer class, which
works fine except assignments - it copies the char* buffer instead of
the pointer.


std::string doesn't do that, it works on the content.
It could be interesting to allow a std::string to use an existing buffer
instead of creating its own though.

May 24 '06 #6

Thanks a lot for the comments. /E.
May 25 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is...
11
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while(...
22
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; ...
19
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not...
2
by: Susan Baker | last post by:
Hi, I have declared a class MyClass in a header file MyClass.h I have then gone onto define the class in MyClass.cpp. This is (roughly) what the definition (.cpp) file looks like: #include...
8
by: Patrick Kowalzick | last post by:
Dear NG, I would like to change the allocator of e.g. all std::strings, without changing my code. Is there a portable solution to achieve this? The only nice solution I can think of, would be...
9
by: Divick | last post by:
Hi all, I have a problem related to std::string class. Is it ok to assign a global string variable to a local string object as shown below? I am trying to print the address of local string...
84
by: Peter Olcott | last post by:
Is there anyway of doing this besides making my own string from scratch? union AnyType { std::string String; double Number; };
11
by: Jacek Dziedzic | last post by:
Hi! I need a routine like: std::string nth_word(const std::string &s, unsigned int n) { // return n-th word from the string, n is 0-based // if 's' contains too few words, return "" //...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.