临时字符串上string :: c_str的用法 [英] Usage of string::c_str on temporary string

查看:183
本文介绍了临时字符串上string :: c_str的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于何时销毁临时对象,这是否有效:

In regards to when temporary objects get destroyed, is this valid:

FILE *f = fopen (std::string ("my_path").c_str (), "r");

在评估了fopen的第一个参数之后或在fopen调用之后,将立即销毁该临时对象.

Will the temporary be destroyed immediately after having evaluated the first argument to fopen or after the fopen call.

使用以下代码进行测试:

Testing with the following code:

#include <cstdio>
using namespace std;
struct A {
        ~A() { printf ("~A\n"); }
        const char *c_str () { return "c_str"; }
};
void foo (const char *s) { printf ("%s\n", s); }
int main () {
        foo (A().c_str());
        printf ("after\n");
        return 0;
}

给予:

c_str
~A
after

表示首先评估整个语句,然后销毁所有临时语句.该排序是由标准强制还是特定于实现的?

which indicates that the whole statement is first evaluated, and then any temporaries are destroyed. Is this ordering mandated by the standard or implementation-specific?

推荐答案

临时表达式将在表达式的末尾被破坏,即;分号. 所以您很安全.

The temporary will be destroyed at the end of the expression, namely the ; semicolon. So you are safe.

§12.2 ...临时对象被销毁,这是其中的最后一步 评估(词汇上)包含 指出它们的创建位置.即使那个评估也是如此 最终引发异常.

§ 12.2 ... Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception.

这篇关于临时字符串上string :: c_str的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆