C++ 如何初始化字符串指针?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11859737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:38:33  来源:igfitidea点击:

how to initialize string pointer?

c++string

提问by Dinesh Dabhi

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

我想将静态值存储在字符串指针中是否可行?

If I do like

如果我喜欢

string *array = {"value"};

the error occurs

错误发生

error: cannot convert 'const char*' to 'std::string*' in initialization

回答by AndersK

you would then need to write

然后你需要写

string *array = new string("value");

although you are better off using

虽然你最好使用

string array = "value";

as that is the intended way to use it. otherwise you need to keep track of memory.

因为这是使用它的预期方式。否则你需要跟踪内存。

回答by juanchopanza

A std::stringpointer has to point to an std::stringobject. What it actually points to depends on your use case. For example:

std::string指针具有指向一个std::string对象。它实际指向的内容取决于您的用例。例如:

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

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

在上面的示例中,p指向string具有自动存储持续时间的本地。当它被销毁时,任何指向它的东西都将指向垃圾。

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 pointersinstead of raw pointers to dynamically allocated objects.

建议您使用智能指针而不是原始指针来动态分配对象。

回答by Rontogiannis Aristofanis

As arrayis an array of strings you could try this:

作为sarray的数组,string你可以试试这个:

int main()
{
  string *array = new string[1]; 
  array[1] = "value";
  return 0;
}

回答by Jerry Coffin

You can explicitly convert the literal to a string:

您可以将文字显式转换为字符串:

 std::string array[] = {std::string("value")};

Note that you have to define this as an array, not a pointer though. Of course, an array mostly makes sense if you have more than one element, like:

请注意,您必须将其定义为数组,而不是指针。当然,如果您有多个元素,则数组通常是有意义的,例如:

string array[] = {string("value1"), string("value2"), string("etc")};