如果返回类型为 static const 时返回非静态局部变量,会发生什么情况
如果您有以下函数:
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;
}
并且在某处使用您所拥有的:
static const map<ushort, ulong> numMap = MakeMap();
编译器实际上会将 numMap 设置为从 MakeMap 返回的地址还是实际上会复制映射?另外,这样做安全吗?
感谢您的反馈!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
返回类型不是
static const map
。它只是const map
。关键字static
适用于该函数。也就是说,它是静态函数,这意味着该函数具有 内部链接*并且不能从其他翻译单元*。* 通过链接了解它们。
现在回到您的问题,首先,返回类型中的
const
没有意义。以下更好:然后您仍然可以编写:
如果您使用良好的编译器,那么很可能它会优化返回值。了解:
The return type is not
static const map<ushort, ulong>
. It's onlyconst map<ushort, ulong>
. The keywordstatic
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:And then you can still write:
If you're using good compiler, then most likely it will optimize on the return value. Read about:
您的函数不会返回地址,而是返回将被复制的对象,因此这样做是安全的。如果您修改代码使 MakeMap 返回一个地址,那么 mymapy 将在某个时刻被销毁(取决于编译选项和编译器),从而导致崩溃。你必须在堆上分配 mymap (用新的)然后销毁它等等......
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 ....
是的,这样做是安全的。对于大多数实际目的,代码的行为就像制作了副本一样(一个好的优化编译器可能会消除需要实际副本)。
此外,正如其他人指出的那样,
static
不是返回类型的一部分。代码中static
的两种用法具有不同的含义。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 ofstatic
in your code have different meaning.