C++中关于string的析构函数
天蓬老师
天蓬老师 2017-04-17 14:26:08
0
3
549

今天偶然用到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();

求解答.

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
刘奇

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

巴扎黑

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

Ty80

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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!