gpt4 book ai didi

c++ - 将 const Key_Type& 传递给 std::map 的 operator[]

转载 作者:行者123 更新时间:2023-11-28 00:26:05 25 4
gpt4 key购买 nike

为什么我不能将 const Key_Type& 传递给 std::map 的 operator[]?我已经完成了这个并且它编译了但是在运行时 std::bad_alloc 异常被抛出:

std::map<std::string, int> myMap;

const std::string& f(const std::string& groupA, const std::string& groupB)
{
return groupA > groupB ? groupA + groupB : groupB + groupA;
}

std::cout << myMap[f("a", "b")];

最佳答案

您正在函数 const std::string& f(const std::string& groupA, const std::string& groupB)

中返回对临时值的引用
return groupA > groupB ? groupA + groupB : groupB + groupA;

+ 运算符返回一个临时值,然后通过引用返回该值。

因此改变按值返回的返回类型(const std::string)解决了这个问题。

正如 @Narek 所指出的,Herb Sutter 如何解释对临时变量使用 const ref。但是我们的问题陈述与 Sutter 讨论的内容不符。为了解释更多,我创建了一个小程序。该程序解释了问题和解决方案:

#include <iostream>
#include <map>

/*
std::map<std::string, int> myMap;

const std::string& f(const std::string& groupA, const std::string& groupB)
{
return groupA > groupB ? groupA + groupB : groupB + groupA;
}*/


struct X{

int member;


X():member(0){
std::cout<<"X ctr "<<std::endl;
}

X(const X& rhs){

std::cout<<"X copy ctr "<<std::endl;
}

~X(){

std::cout<<"X dtr"<<std::endl;
member = -1;
}
};

void f2(const X& obj){

std::cout<<"func "<<obj.member<<std::endl;

}

const X& f3(){
return X();
}

X f4(){
return X(); //ideally not a good idea, exception is
//http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
}

int main()
{
/* myMap["ba"] = 1;
std::cout <<"key "<< f("a", "b")<<std::endl;
std::cout << myMap[f("a", "b")]<<std::endl;*/

std::cout << "-----Faulty Case-----------"<<std::endl;

//reference returned by f3 is local to f3 call and
//is destructed as soon as f3() is out of stack
//and hence the reference in f2() is not valid
f2( f3() );

std::cout <<std::endl<< "-----Correct way-----------"<<std::endl;

//A temporary object is returned by f4 which is then referred by reference in f2.
//This reference is alive in stack of f2 and hence can be used inside
//f2 with valid results.
//As explained in following article, the refernce should remain
//alive in stack to use temporary objects.
//http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
f2( f4() );

//note in previous expression, f4 returns by value but still copy ctr is not invoked,
//this I believe is Return Value Optimization (might be compiler dependent)

return 0;
}

这个程序的输出:

main.cpp: In function �const X& f3()�:
main.cpp:41:14: warning: returning reference to temporary [-Wreturn-local-addr]
return X();
^

Executing the program....
$demo
-----Faulty Case-----------
X ctr
X dtr
func -1

-----Correct way-----------
X ctr
func 0
X dtr

我希望这会拨开乌云。

关于c++ - 将 const Key_Type& 传递给 std::map 的 operator[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24990370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com