tags:

views:

114

answers:

3

Hello,

I have some gaps in the understanding of string::assign method. Consider the following code:

char* c = new char[38];
strcpy(c, "All your base are belong to us!");
std::string s;
s.assign(c, 38);

Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer; i.e. doesn't allocate new memory and uses directly my address. If it copies, then what is the difference between assign and operator=? If it doesn't copy, then does it free the memory or it is my responsibility?

Thank you.

+12  A: 

Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer;

The STL string method assign will copy the character array into the string. If the already allocated buffer inside the string is insufficient it will reallocate the memory internally. The STL string will not take ownership of the original array.

If it copies, then what is the difference between assign and operator=?

Both ought to act in the same way, but there are a number of overloads to the STL assign method which give you more control over what happens. Take a look at this page for more information.

UPDATE: The MSDN has a number of examples of the various assign overloads.

If it doesn't copy, then does it free the memory or it is my responsibility?

No, the original pointer to the character array is still your responsibility.

Konrad
A: 

As far as I can remember, it is up to the implementation of your compiler. Some may use copy-on-write optimizations and therefore create no copy until you modify the value. However, most implementations will just copy the string.

But, all implementations will take care of the cleanup - so no need for you to manually free the strings memory (that's what string objects are all about). Of course you have to free your string objects, if created on the heap (or use a smartpointer) ;)

Assign and operator= may be implemented in terms of each other as they do the same thing - depending on which version of assign is called (for all overloads see cpp reference).

fmuecke
Copy-on-write can only be used hen assigning one string to another - it can't be used when assigning a char *.
anon
+3  A: 

It copies. The difference between assign and operator= is that you can specify the number of characters to be copied including null characters. The operator= just copies the c-string up to the first null byte.

A. Levy