简体   繁体   English

字符串是否动态分配?

[英]Is string dynamically allocated?

I have got a quick question. 我有一个简单的问题。 I have the following code: 我有以下代码:

class Class1
{
    Class1();
    ~Class1();
    void func1();
private:
    char* c;

}

void Class1::func1()
{
    string s = "something";
    this->c = s.c_str();
}

will c store "something" when func1() finishes? c存储"something"func1()完成?

No. It will invoke undefined behavior instead. 不会。它会调用未定义的行为。 (if you dereference the pointer, anyway.) Since s is a block-scope object with automatic storage duration, it is destroyed when the function returns, and that renders the pointer returned by .c_str() invalid. (如果你取消引用指针,无论如何。)因为s是具有自动存储持续时间的块范围对象,所以当函数返回时它会被销毁,并且会使.c_str()返回的指针无效。


Why not use an std::string member variable instead? 为什么不使用std::string成员变量呢?

s is a local variable of type std::string in Class::func1 . sClass::func1 std::string类型的局部变量。 Once func1() finishes, the string s will go out of scope. 一旦func1()完成,字符串s将超出范围。

Any pointers you have with the address of s stored in them will become dangling pointers. 你有地址的指针s存储在其中将成为悬摆指针。

It will store a dangling pointer that you must not access. 它将存储您不能访问的悬空指针。 It may contain the string "something" or it may not. 它可能包含字符串"something"或者可能不包含。 It doesn't matter, because accessing it is undefined behaviour, and should be avoided completely. 没关系,因为访问它是未定义的行为,应该完全避免。

If you want to copy the string do this: 如果要复制字符串,请执行以下操作:

c = strdup( c.c_str() );

And don't forget to free(c) in ~Class1() 并且不要忘记在~Class1() free(c) ~Class1()

Beware that if you call func1 twice, you will leak memory. 请注意,如果你两次调用func1 ,你将泄漏内存。 You probably want to initialise c to NULL in the constructor, and call free(c) before reassigning it in func1 . 您可能希望在构造函数中将c初始化为NULL ,并在func1重新分配之前调用free(c)

Surely a better approach is to store a std::string instead of a char* , which manages memory properly for you. 当然,更好的方法是存储std::string而不是char* ,它可以为您正确管理内存。

The variable s , will go out of scope once control exits that block, at which point its destructor will be called. 一旦控制退出该块,变量s将超出范围,此时将调用其析构函数。

When is an object "out of scope"? 什么时候对象“超出范围”?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM