gpt4 book ai didi

c++ - std::map 表初始化是否优化?

转载 作者:太空狗 更新时间:2023-10-29 20:47:06 25 4
gpt4 key购买 nike

考虑到问题末尾的示例,是否每次调用函数 GetName() 时都会创建 map 对象?
还是要对创建进行优化并创建为一些查找表?

#include <iostream>
#include <sstream>
#include <map>
#include <string>
#include <boost/assign/list_of.hpp>

enum abc
{
A = 1,
B,
C
};

std::string GetName( const abc v )
{
const std::map< abc, std::string > values =
boost::assign::map_list_of( A, "A" )( B, "B" )( C, "C" );
std::map< abc, std::string >::const_iterator it = values.find( v );
if ( values.end() == it )
{
std::stringstream ss;
ss << "invalid value (" << static_cast< int >( v ) << ")";
return ss.str();
}
return it->second;
}

int main()
{
const abc a = A;
const abc b = B;
const abc c = C;
const abc d = static_cast< abc >( 123 );

std::cout<<"a="<<GetName(a)<<std::endl;
std::cout<<"b="<<GetName(b)<<std::endl;
std::cout<<"c="<<GetName(c)<<std::endl;
std::cout<<"d="<<GetName(d)<<std::endl;
}

最佳答案

在语义和概念上以及关于神圣标准,它每次都会被创建。

剩下的取决于你的编译器以及你如何支持她:

可能编译器可以内联调用,然后将推导的不变量移到外面到单点初始化。

可能编译器不喜欢你的函数有外部链接,所以没有内联它,然后就很难了从其他函数中看到不变性。

可能 编译器将始终检查变量常量并使用一次性初始化当它可以查看内部并验证 boost::assign::map_list_of( A, "A")( B, "B")( C, "C")不会改变全局状态。

很多因素,唯一可以确定的方法是查看生成的代码。


响应报价请求:

3.7.2.3 [basic.std.auto]:

If a named automatic object has initialization or a destructor with side effects, it shall not be destroyed before the end of its block, nor shall it be eliminated as an optimization even if it appears to be unused, except that a class object or its copy may be eliminated as specified in"

这基本上意味着它要么有副作用,在这种情况下它不会被消除,要么没有,在这种情况下它在 C++ 中很难观察到;这有效地意味着:

观察到的行为总是好像每次都被调用

换句话说:没有办法保证初始化只用自动存储发生一次,所以永远不要假设相反

关于c++ - std::map 表初始化是否优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423210/

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