临时字符串上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.