Home  >  Q&A  >  body text

C++中关于string的析构函数

今天偶然用到string, 发现string的析构函数特别奇怪, 直接调用居然报错, 代码如下 :

int main(int argc, char* argv[]) {
    std::string x = "123";
    x.~string();
    return 0;
}

这是报错信息 :

/Users/zhangzhimin/ClionProjects/geek/main.cpp:16:8: error: identifier 'string' in object destruction expression does not name a type
    x.~string();

求解答.

天蓬老师天蓬老师2764 days ago583

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 14:28:08

    What’s funny upstairs?

    The correct answer is that std::string is actually just a typedef of std::basic_string<char>, so if you want to adjust its destructor:

    x.~basic_string()

    In addition, your string is not new, so there is no need to deconstruct it

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 14:28:08

    You successfully caught my attention. . .

    If the namespace has not been opened with the using statement before, calling the destructor should be written like this:
    x.std::string::~string();

    I guess you wrote this to manually destroy the object in the space configurator

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:28:08

    Ah, string is indeed derived from the typedef of basic_string<>, but string can directly call ~string(). The topic may be due to the lack of std namespace. Practice is the standard for testing truth. I tried compiling and running successfully. There is a description of string here. http://www.cplusplus.com/refe...

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string str("hello");
        str.~string();
        return 0;
    }

    reply
    0
  • Cancelreply