Deleting char* after assigning it to a string variable

后端 未结 3 679
夕颜
夕颜 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:23

    There is no problem, as long as newChar points to a null-terminated string, and is not null itself.

    std::string has constructor that allows an implicit construction from a const char*. It makes a copy of the character string represented by the input const char * so it works under the assumption that the char* is a null terminated string, since there is no other way to know how many characters to copy into the string's own data storage. Furthermore, a NULL pointer is actually disallowed by the standard.

    0 讨论(0)
  • 2021-01-23 04:36

    No, because std::string copies the contents of your char*, so you're free to delete it when you no longer need it.

    0 讨论(0)
  • 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 <stdio.h>
    #include <string.h>
    #include <string>
    #include <iostream>
    
    int main()
    {
        std::string testStr = "whats up ...";
        unsigned strlen = testStr.length();
    
        std::vector<char> 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.

    0 讨论(0)
提交回复
热议问题