Warm tip: This article is reproduced from stackoverflow.com, please click
c++ temporary-objects

How many temporary objects are created in this initialization?

发布于 2020-03-27 15:26:45

I have this initialization:

const char* str = std::string("a").c_str();

How many temporary objects are created in this initialization?

Can "a" be considered an temp. object?

I know std::string("a") is a temp. object.

The result of c_str() is a object, str stores it. So it's not a temp. object, right?

Questioner
João Paulo
Viewed
19
NathanOliver 2019-04-26 20:32

"a" is a string literal of type const char[2], so it is an object.

std::string("a") is a prvalue expression and is not a temporary object (yet). When you call c_str() you materialize a temporary object and call c_str() on it getting a pointer to the data of a temporary object.

You then assign the address of the pointer to str so now str holds the address to a pointer to the data of a temporary object. At the end of that full expression the materialized temporary object is destroyed invalidating a iterators/pointers/references to that temporaries data.

That means str now points to memory you no longer own and is called a dangling pointer. Doing anything to it other that assigning it a different address is undefined behavior.

So you have 2 objects when it is all over. A dangling pointer (str), and a string literal ("a").