473,241 Members | 1,430 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,241 software developers and data experts.

Help with std string

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 buffer and then I
print the address of global string buffer and come out to be same, but
I assume that as soon as func method has returned that temporaryString
string must have been deleted and thus the buffer that it might be
holding might get freed unless that buffer is being reused by the
string class.

So doing something like below might depend on the implementation of
std::string class. Can I assume that it would do the right thing?

string globalString;

void func()
{
string temporaryString = "some value";
printf("Address of local strings buffer %x\n",
temporaryString.c_str());
globalString = temporaryString;
return;
}

void someOtherFunc()
{
func();
//Now use the globalString but the address printed below is
same as the one
//printed by the function func which might get deleted /freed
by string class
printf("Address of global string buffer
%x\n",globalString.c_str());
}

Another question I have is related to STL. I was storing char * 's in
STL containers previously, since now I am converting all my char *'s to
string to avoid memory leaks, I wanted to know that shall I make
container of string or container of string references.

For example:
map<const string&, const string &, myComparator>
or
map<const string, const string , myComparator>

Is there some guidelines for that?

Thanks,
Divick

Jan 23 '06 #1
9 7400
* Divick:
Is it ok to
assign a global string variable to a local string object as shown
below?
yes
[snip] So doing something like below might depend on the implementation of
std::string class. Can I assume that it would do the right thing?
no

you have undefined behavior

string globalString;

void func()
{
string temporaryString = "some value";
printf("Address of local strings buffer %x\n",
temporaryString.c_str());
undefined behavior here, c_str() yields a pointer, %x says it's int
[snip] Another question I have is related to STL. I was storing char * 's in
STL containers previously, since now I am converting all my char *'s to
string to avoid memory leaks, I wanted to know that shall I make
container of string or container of string references.

For example:
map<const string&, const string &, myComparator>
or
map<const string, const string , myComparator>

Is there some guidelines for that?


a standard container element must be copyable, your first example isn't.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jan 23 '06 #2
Alf P. Steinbach wrote:
* Divick:
Is it ok to
assign a global string variable to a local string object as shown
below?
yes
[snip]
So doing something like below might depend on the implementation of
std::string class. Can I assume that it would do the right thing?


no


Well, the string class does "the right thing". But I agree that the
reference of "it" in the OPs question is not quite as clear as it could be.
you have undefined behavior
Yes, but that stems from inappropriate use of printf() and not from problems
with the string class.
string globalString;

void func()
{
string temporaryString = "some value";
printf("Address of local strings buffer %x\n",
temporaryString.c_str());


undefined behavior here, c_str() yields a pointer, %x says it's int

To the OP: Let us remove all possibly distracting clutter from your code.
string globalString;

void func() {
string temporaryString = "some value";
globalString = temporaryString;
}

void someOtherFunc() {
func();
std::cout << globalString << '\n';
}
Executing someOtherFunc() will neither produce undefined behavior nor will
it leak memory or ill-behave in any other way. What you observed when
printing out addresses (or some numbers arising from undefined behavior, as
Alf Steinbach pointed out) could just be an indication that your
std::string implementation uses reference counting as an optimization for
string assignments.

Generally, std::string is designed to handle memory management correctly
behind the scenes. That is one of its primary virtues. In particular,
destruction of temporaryString afert the assignement

globalString = temporaryString;

will not affect globalString in any way.
Best

Kai-Uwe Bux
Jan 23 '06 #3
>>undefined behavior here, c_str() yields a pointer, %x says it's int
I don't understand why it has undefined behavior? I understand that
string class must be using some reference counting mechanism to avoid
deletion of data once it has been assigned to another string, but isn't
it that the addresses for both of them would be same. So what is the
harm in printing it.

By the way I am just printing the addresses, but obviously my intention
is not to use that address for some other purpose. I simply wrote that
to specify that the addresses are same for both the addresses and was
curious that does std::string class use reference counting or not.
Since string class uses reference counting (as it seems to me from
above discussion), the addresses would be same (due to which only I
started this thread). Had I known that on whatever platform the string
class would do some reference counting, I wouldn't have asked this
question altogether. Since I was not sure whether string class uses
reference counting or not, that's why I posted to this thread.

Is there something that I am missing in the above discussion or what?

Thanks,
Divick

Jan 25 '06 #4
Divick wrote:
undefined behavior here, c_str() yields a pointer, %x says it's int
I don't understand why it has undefined behavior?


Because the standards say so. C++ inherits printf() from C. The C standard
defines printf() in terms of fprintf(). About this, it says in clause
7.19.6.1/9:

If a conversion specification is invalid, the behavior is undefined.223)
If any argument is not the correct type for the corresponding coversion
specification, the behavior is undefined.

I understand that
string class must be using some reference counting mechanism to avoid
deletion of data once it has been assigned to another string, but isn't
it that the addresses for both of them would be same. So what is the
harm in printing it.
No harm in printing the pointer. The "harm" arises from treating a pointer
as an int within printf(). That is undefined behavior, although on most
platforms, I would expect it to behave exactly as you expected.

By the way I am just printing the addresses, but obviously my intention
is not to use that address for some other purpose. I simply wrote that
to specify that the addresses are same for both the addresses and was
curious that does std::string class use reference counting or not.
Since string class uses reference counting (as it seems to me from
above discussion), the addresses would be same (due to which only I
started this thread). Had I known that on whatever platform the string
class would do some reference counting, I wouldn't have asked this
question altogether. Since I was not sure whether string class uses
reference counting or not, that's why I posted to this thread.
Well, and I hope the responses in this thread have helped understanding why
you got the output you got and why there is nothing wrong with using the
global variables. The undefined behavior thing is just a tangent. Do get
sidetracked.

Is there something that I am missing in the above discussion or what?


I don't think so.

Best

Kai-Uwe Bux
Jan 25 '06 #5
>>Because the standards say so. C++ inherits printf() from C. The C standard
defines printf() in terms of fprintf(). About this, it says in clause
7.19.6.1/9:
If a conversion specification is invalid, the behavior is undefined.223)
If any argument is not the correct type for the corresponding coversion
specification, the behavior is undefined.


What is the correct conversion specifier for printing addresses if not
%x ?

Rest is pretty clear now. Thanks for that.

Divick

Jan 25 '06 #6
Divick wrote:
What is the correct conversion specifier for printing addresses if not
%x ?

%p
Stephan

Jan 25 '06 #7
Stephan Brönnimann wrote:
Divick wrote:
What is the correct conversion specifier for printing addresses if
not %x ?

%p

Correct, but %p expects a void*. This is one of those places where a
cast is required, as printf() is a variadic function.


Brian
Jan 25 '06 #8
Default User wrote:
Stephan Brönnimann wrote:
Divick wrote:
What is the correct conversion specifier for printing addresses if
not %x ?

%p

Correct, but %p expects a void*. This is one of those places where a
cast is required, as printf() is a variadic function.


A pointer of any type can be converted to void*, without a cast.
If you're really worried that the size of void* is different from the
one of A* then do the cast.

Stephan

Jan 25 '06 #9
Stephan Brönnimann wrote:
Default User wrote:
Stephan Brönnimann wrote:
Divick wrote:
> What is the correct conversion specifier for printing addresses
> if not %x ?
%p

Correct, but %p expects a void*. This is one of those places where a
cast is required, as printf() is a variadic function.


A pointer of any type can be converted to void*, without a cast.


Not with a variadic function.

Brian

Jan 25 '06 #10

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

Similar topics

6
by: wukexin | last post by:
Help me, good men. I find mang books that introduce bit "mang header files",they talk too bit,in fact it is my too fool, I don't learn it, I have do a test program, but I have no correct doing...
7
by: Alan Bashy | last post by:
Please, guys, In need help with this. It is due in the next week. Please, help me to implement the functions in this programm especially the first three constructor. I need them guys. Please, help...
1
by: wukexin | last post by:
I write my own class Cfile, I want to know what about implement ctime().Who help me? My use function ctime, I sign it with $$$. my class Cfile: #------------------------ file.h...
3
by: Colin J. Williams | last post by:
Python advertises some basic service: C:\Python24>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> With...
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
18
by: James Radke | last post by:
Hello, We are currently using a user DLL that when working in VB 6.0 has a user defined type as a parameter. Now we are trying to use the same DLL from a vb.net application and are having...
16
by: Allen | last post by:
I have a class that returns an arraylist. How do I fill a list box from what is returned? It returns customers which is a arraylist but I cant seem to get the stuff to fill a list box. I just...
1
by: Rahul | last post by:
Hi Everybody I have some problem in my script. please help me. This is script file. I have one *.inq file. I want run this script in XML files. But this script errors shows . If u want i am...
22
by: KitKat | last post by:
I need to get this to go to each folders: Cam 1, Cam 2, Cam 4, Cam 6, Cam 7, and Cam 8. Well it does that but it also needs to change the file name to the same folder where the file is being...
6
by: JonathanOrlev | last post by:
Hello everyone, I have a newbe question: In Access (2003) VBA, what is the difference between a Module and a Class Module in the VBA development environment? If I remember correctly, new...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.