C++ 字符串 vs vector<char> vs 动态数组

c++ strings vs vector<char> vs dynamic arrays

我试图使用 char* 指针来引用 stringsvector<char> & dynamic arrays & 我对以下结果有疑问:-

代码 1:-

#include <iostream>
#include <string>
using namespace std;
int main()
{
    cout<<"executing...\n";
    string s="abcde";
    char *c=&s[0];
    cout<<c<<"\n";
    s.~string();
    cout<<c<<"\n";
    cout<<"executed";
    return 0;
}

这段代码的输出是:-

executing...
abcde
abcde
executed 

代码 2:-

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    cout<<"executing...\n";
    vector<char> v {'a','b','c','d','e'};
    char *p=&v[0];
    cout<<p<<"\n";
    v.~vector();
    cout<<p<<"\n";
    cout<<"executed";
    return 0;
}

这段代码的输出是:-

executing...
abcde

executed 

代码 3(使用动态数组):-

#include <iostream>
using namespace std;
int main()
{
    cout<<"executing...\n";
    char* c=new char[20] {'a','b','c','d','e'};
    char *p=c;
    cout<<p;
    delete[] c;
    cout<<"\n"<<p<<"\n";
    cout<<"executed";
    return 0;
}

此代码的输出类似于代码 2:-

executing...
abcde

executed 

我想知道为什么 CODE 1 产生的输出与 CODE 2 & CODE 3 不同? string 有什么问题,它的行为与 vector<char> & dynamic arrays 不同?

已删除的所有代码访问数据片段,没有定义的行为。因此,任何进一步的假设都是没有意义的,留给单个案例。无论您访问的是 vectorchar*string,都没有区别:它们始终是相同的违规行为。

好吧,我想这个例子足以说明 stringvector 的对象被删除了两次,因此导致 undefined behaviour :-

#include <iostream>
using namespace std;

class X
{
    int x;
    public:
    X()
    {
        cout<<"constructing\n";
    }

    // other member functions...

    ~X()
    {
        cout<<"destroying\n";
    }
};

int main()
{
    X object;
    object.~X();
    return 0;
}

输出将是:-

constructing
destroying
destroying

当行为未定义时,思考 "WHY SUCH AN OUTPUT" 等东西是没有用的!甚至我对 reference counting of C++ strings 也有疑问,但正如许多人所说 strings 不再是 reference counted,所以 CODE 1 也产生了 undefined behaviour。但是我喜欢你尝试代码。有必要正确地学习一门语言。坚持下去!!!