类的动态分配的char数组中的WTF行为

问题描述 投票:0回答:1

每当我运行下面的代码时,应用程序便崩溃了。在调试期间,我看到str对象在main()的第二行之后正在自我破坏。这对我来说是个谜。尝试自己运行它:

#include<iostream>

class String {
private:
    char* string = nullptr;
    int length = 0;

public:
    String(const char str[]) {
        for (length; str[length] != '\0'; ++length);

        string = new char[length + 1]{};

        for (int i{}; i < length; ++i)
            string[i] = str[i];

        string[length] = '\0';
    }

    ~String() {
        delete[] string;
    }

    auto print() {
        for (int i{}; i < length; ++i)
            std::cout << string[i];
        std::cout << '\n';
        return *this;
    }

    auto getStrPtr() {
        return string;
    }
};

int main() {
    String str("123");
    auto strPtr{ str.print().getStrPtr() };
    strPtr[0] = '3';
}

我想念什么吗?

c++ class dynamic-memory-allocation
1个回答
0
投票

str对象未在main的第二行上销毁。 str的临时副本已销毁。

临时句在完整表达的结尾处被销毁。这很正常。


您的类删除了析构函数中的指针成员,但无法使该类的指针唯一性保持不变。当str的析构函数删除与临时对象的析构函数删除相同的指针值时,程序的行为是不确定的。甚至在strPtr[0] = '3';通过析构函数中删除的指针进行间接操作之前,行为是不确定的。

解决方案:使用智能指针,而不是拥有裸指针。

© www.soinside.com 2019 - 2024. All rights reserved.