开发者

Object allocation in C++

char *myfunc() {
    char *temp = "string";
    return temp;
}

In this piece of code, where does the allocation of the object pointed to by temp happen and what would be its scope?

Is this funct开发者_如何转开发ion a valid way to return a char* pointer?


Is the code correct?

Yes your code is (almost) fine, because "string" is a string literal and located in static storage.

Note: A pointer is just a variable which stores a memory address. This line simply stores the address of the string literal "string" inside a variable called temp.

char *temp = "string";

The C++ standard guarantees that the string literal will stay in memory for the duration of the program as defined below. Which means you are free to use that memory address in any scope anywhere during the whole life of your program.


Why?

The C++03 standard (current) has this to say:

An ordinary string literal has type “array of n const char” and static storage duration (3.7),

And section 3.7.1 - 1:

All objects which neither have dynamic storage duration nor are local have static storage duration. The storage for these objects shall last for the duration of the program.


Warning:

In your code you are returning a char*, you should really be returning a const char *. It is undefined behavior if you try to modify a string literal, and your function return value shouldn't pretend to allow it.

On a related side note to the warning. If you have in your code in 2 different places a string called "string" then whether or not they are distinct strings is implementation defined.


This piece of code works (and is correct) because the object "string" is static data, which is "allocated" (so to say) during compilation - the linker places it in a special section of the executable.

But standards-compliant C++ should say const char* instead of char* when referring to static data.


As has been mentioned it's allocated at compilation time; it's a literal.

But in c++ it's not as valid as it could be because the pointer doesn't point to const char. In general, it's something you should consider doing in a very different way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜