gpt4 book ai didi

c++ - 编译器会排除未使用的模板代码吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:58 24 4
gpt4 key购买 nike

当您使用包含许多方法(如 vector)的模板并编译您的代码时,编译器会丢弃未使用的方法中的代码吗?

最佳答案

模板除非被使用,否则不会被实例化,所以实际上没有代码可以丢弃。

标准说 (14.7.1/10)

An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class, or a static data member of a class template that does not require instantiation. It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated. The use of a template specialization in a default argument shall not cause the template to be implicitly instantiated except that a class template may be instantiated where its complete type is needed to determine the correctness of the default argument. The use of a default argument in a function call causes specializations in the default argument to be implicitly instantiated.

因此,如果您可以避免使模板的成员函数成为虚函数,编译器将不会为它们生成任何代码(如果编译器足够聪明,这也可能适用于虚函数)。

关于c++ - 编译器会排除未使用的模板代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11890996/

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