What happens if you return a non-static local when the return type is static const
If you have the following function:
开发者_StackOverflow中文版static const map<ushort, ulong> MakeMap()
{
map<ushort, ulong> mymap;
for(int i=0; i<myTableSize; i++)
{
mymap[myTable[i].x] = myTable[i].y;
}
return mymap;
}
and somewhere use you have:
static const map<ushort, ulong> numMap = MakeMap();
will the compiler actually set numMap to the address returned from MakeMap or will it actually make a copy of the map? Also, is this even safe to do?
Thanks for your feedback!
The return type is not static const map<ushort, ulong>
. It's only const map<ushort, ulong>
. The keyword static
applies to the function. That is, it's the function which is static which means the function has internal linkage* and cannot be called from other translation unit*.
* Go through the links to know about them.
Now coming back to your question, first of all, const
in the return type doesn't make sense. The following is better:
//remove the static also if you don't want it to have internal linkage
static map<ushort, ulong> MakeMap();
And then you can still write:
const map<ushort, ulong> numMap = MakeMap();
If you're using good compiler, then most likely it will optimize on the return value. Read about:
- Return Value Optimization
Your function is not returning an address but on object which will be copied so it's safe to do so. If you modify your code so MakeMap return an address , then mymapy will be destroyed at some point (depending of compilation options and compiler) and so that will crash. You have to allocate mymap on the heap (with a new) and then destroy it etc ....
Yes, it is safe to do this. For most practical purposes, the code will behave as if a copy were made (a good optimizing compiler may eliminate the need for an actual copy).
Also, as others have pointed out, static
isn't part of the return type. The two uses of static
in your code have different meaning.
精彩评论