2

If I convert a std::string into a CString using something like:

std::string ss("Foo");
CString cs( ss.c_str() );

Does the CString copy the characters from ss or does it simply copy the char* pointer?

My understanding of the c_str() function is that it returns a pointer to a character array owned by the std::string. So having a CString using this internally would seem like a really bad idea as any nonconstant method on either of them would then invalidate the pointer held in the other.

hmjd
  • 120,187
  • 20
  • 207
  • 252
Nigel Hawkins
  • 824
  • 1
  • 8
  • 23

3 Answers3

2

The CString constructor that takes a const char* will copy the data into its internal structure. It's the same as doing this:

CString test = "This is a test" or even this CString test("This is a test")

Chad
  • 18,706
  • 4
  • 46
  • 63
1

Documentation of CString constructor (link) says:

The constructors copy the input data into new allocated storage.

So, your data must be copied.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
1

The documentation says that the string will be copied, so it will not manipulate the std::string buffer directly.

CString( LPCSTR lpsz );

lpsz - A null-terminated string to be copied into this CString object.

Attila
  • 28,265
  • 3
  • 46
  • 55