通过静态局部变量的参考/指针返回
return by reference/pointer of a static local variable
我对为什么如果我通过参考获得静态unordered_map被清除,而不是通过指针获得它的原因...(您可以在此处执行代码:http:/http://cpp.sh/4ondg)
是因为当引用范围范围内时,其破坏者会被调用?如果是这样,那么第二获得功能会得到什么?
class MyTestClass {
public:
static std::unordered_map<int, int>& getMap() {
static std::unordered_map<int, int> map;
return map;
}
static std::unordered_map<int, int>* getMapByPointer() {
static std::unordered_map<int, int> map;
return ↦
}
};
int main()
{
// By reference
{
auto theMap = MyTestClass::getMap();
std::cout << theMap.size() << std::endl;
theMap[5] = 3;
std::cout << theMap.size() << std::endl;
}
{
auto theMap = MyTestClass::getMap();
std::cout << theMap.size() << std::endl;
theMap[6] = 4;
std::cout << theMap.size() << std::endl;
}
// By pointer
{
auto theMap = MyTestClass::getMapByPointer();
std::cout << theMap->size() << std::endl;
(*theMap)[5] = 3;
std::cout << theMap->size() << std::endl;
}
{
auto theMap = MyTestClass::getMapByPointer();
std::cout << theMap->size() << std::endl;
(*theMap)[6] = 4;
std::cout << theMap->size() << std::endl;
}
}
做
auto theMap = MyTestClass::getMap();
theMap
的类型被推论为std::unordered_map<int, int>
- 不是参考。因此,函数调用返回的引用被复制到本地变量theMap
中;修改theMap
时,您只在修改此副本。
存储参考,将其声明为 auto&
:
auto& theMap = MyTestClass::getMap();
然后您将按照预期修改原始对象。
当将静态图分配给本地变量时,您会无意中复制静态图。在:
auto theMap = MyTestClass::getMap();
auto
被推论为std::unordered_map<int, int>
,而不是std::unordered_map<int, int>&
,它导致新对象从返回的参考文献中复制进行委员会化。因此,theMap
是与静态地图完全独立的对象。
指针版本没有此问题,因为将类型推荐为指针,因此复制的唯一内容是指针值本身,该值总是指向相同的(静态)对象。
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 指向 std::unrodered_map 中元素的指针返回'Read access violation'
- 为什么要为指针返回类型返回一系列字符?
- Visual C 运行时:Malloc将指针返回到已经使用的内存(包含实际字符串)
- 将原始指针返回到智能指针
- 从函数中的指针返回对象,例如链接列表
- 将指针返回使用New创建的数组数组
- 查找并将指针返回向量中的对象
- 函数可以将指针返回其自己的类型
- 指针返回值的地址
- 为什么静态指针返回函数中有一个"静态"键?
- 从弱指针返回类型返回共享指针
- 如何将C++引用和指针返回转换为 C++/CLR
- 从指针返回对象时出现意外的析构函数调用
- 阵列指针返回垃圾
- (C )当在同一类中调用时,污点指针返回正确的值,而从MAIN调用时为0
- C 从指针返回到成员功能
- 在构造函数以外的任何其他位置访问相机时,我的相机指针返回 null
- 从取消引用的指针返回原始指针
- 指针返回