Does std::string do a shallow copy in copy construtor and assign operator ?

S

suman.nandan

Hi Experts,
In the following code (sorry for using C printf in the code !) :
----------------------------------------------
#include <string>
#include<cstdio>

using namespace std;

int main ()
{
string a1 = "abcd";
string a2;

a2 = a1;

printf("Address of a1.c_str() is = %u\n", a1.c_str());
printf("Address of a2.c_str() is = %u\n", a2.c_str());
}
---------------------------------------------
The output I am getting is :
Address of a1.c_str() is = 159920148
Address of a2.c_str() is = 159920148
----------------------------------------------
I seems that the copy happening here is a shallow one.
I have also tried with copy constructor.
This seems to be counter intuitive. Is this expected ?

Thanks,
Suman.
 
I

Ian Collins

Hi Experts,
In the following code (sorry for using C printf in the code !) :
----------------------------------------------
#include <string>
#include<cstdio>

using namespace std;

int main ()
{
string a1 = "abcd";
string a2;

a2 = a1;

printf("Address of a1.c_str() is = %u\n", a1.c_str());
printf("Address of a2.c_str() is = %u\n", a2.c_str());
}
Yes, the there is no need to copy the string data unless either object
is modified, so your std::string probably uses a reference counter for
the raw data. Try modifying either string and see what you get.
 
J

John Harrison

Hi Experts,
In the following code (sorry for using C printf in the code !) :
----------------------------------------------
#include <string>
#include<cstdio>

using namespace std;

int main ()
{
string a1 = "abcd";
string a2;

a2 = a1;

printf("Address of a1.c_str() is = %u\n", a1.c_str());
printf("Address of a2.c_str() is = %u\n", a2.c_str());
}
---------------------------------------------
The output I am getting is :
Address of a1.c_str() is = 159920148
Address of a2.c_str() is = 159920148
----------------------------------------------
I seems that the copy happening here is a shallow one.
I have also tried with copy constructor.
This seems to be counter intuitive. Is this expected ?

Thanks,
Suman.

Probably string is delaying the copy until you modify one of the
strings. String does *not* do shallow copies, but when the copy happens
is another matter.

Try googling for 'copy on write'

john
 

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,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top