I have executed the below code and it works perfectly. Since it is about pointers, I just want to be sure. Though I\'m sure that assigning char* to string makes a copy and even
The code is fine, if you look at the constructors of std::basic_string here you'll be able to deduce that std::string has two interesting constructors here:
(4) string(char const*,
size_type count,
Allocator const& alloc = Allocator() );
(5) string(char const* s,
Allocator const& alloc = Allocator() );
Both perform a copy, and the first reads exactly count characters whilst the second reads up until it encounters a NUL-character.
That being said, I actively encourage you not to use dynamic allocation here. If you want a temporary buffer to play with, consider using std::vector instead.
#include
#include
#include
#include
int main()
{
std::string testStr = "whats up ...";
unsigned strlen = testStr.length();
std::vector buffer(strlen+1);
memset(&buffer[0],'\0',strlen+1);
memcpy(&buffer[0], testStr.c_str(), strlen);
std::cout << " :11111111 : " << &buffer[0] << "\n";
std::string newStr(&buffer[0]);
std::cout << " 2222222 : " << newStr << "\n";
buffer.clear();
std::cout << " 3333333 : " << newStr << "\n";
}
Note: both vector and string have range-constructors, to build them from a range of iterators, that I purposefully refrained from using to avoid confusion and you being overwhelmed. Just know that you could have used them to avoid calling memcpy and risking a buffer overflow though.