how to initialize string pointer?

后端 未结 4 1519
再見小時候
再見小時候 2021-01-13 02:58

I want to store the static value in string pointer is it posible?

If I do like

string *array = {\"value\"};

the error occurs

4条回答
  •  别那么骄傲
    2021-01-13 03:09

    A std::string pointer has to point to an std::string object. What it actually points to depends on your use case. For example:

    std::string s("value"); // initialize a string
    std::string* p = &s; // p points to s
    

    In the above example, p points to a local string with automatic storage duration. When it it gets destroyed, anything that points to it will point to garbage.

    You can also make the pointer point to a dynamically allocated string, in which case you are in charge of releasing the resources when you are done:

    std::string* p = new std::string("value"); // p points to dynamically allocated string
    // ....
    delete p; // release resources when done
    

    You would be advised to use smart pointers instead of raw pointers to dynamically allocated objects.

提交回复
热议问题