简体   繁体   中英

How many temporary objects are created in this initialization?

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?

"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" ).

There is only one. The string.

"a" is a literal, which type is const char[] of approriate size, it has a static storage. So, it's not a temporary for sure.

str , and a return value of c_str() are const char pointers as well.

No other object are created.

Can "a" be considered an temp. object?

Technically, it not well defined .

It does not have a defined lifetime. Technically using it does not has defined behavior. It is not of the construct that officially begins the lifetime of an object.

In practice you can use it (obviously).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM