Deleting char* after assigning it to a string variable

后端 未结 3 681
夕颜
夕颜 2021-01-23 04:14

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

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 04:39

    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.

提交回复
热议问题