c++ - 为什么 boost::call_traits 通过引用传递像 pair<char, char> 这样的小对象?

标签 c++ boost parameter-passing

我需要一种方法来决定是通过复制还是通过常量引用传递任意类型 T(例如,如果 T 足够小,则复制 if,否则通过常量引用传递)。为了避免重新发明轮子,我尝试了 Boost Call Traits。

正如预期的那样,基本类型按值传递,复杂类型如 std::string通过引用传递。然而,微小的非基本类型也通过引用传递,例如 std::pair<char, char> ,这似乎不是最佳选择。我假设一切都达到 sizeof(void*)将按值传递。

一般来说,Boost 库质量很高,所以我可能遗漏了一些东西。

这是我的测试代码:

#include <iostream>
#include <type_traits>
#include <tuple>
#include <boost/call_traits.hpp>

template <typename TYPE>
void test(const char* type_name)
{
  typedef typename boost::call_traits<TYPE>::param_type T;  
  if(std::is_reference<T>::value)        
    std::cout << type_name << " is passed by reference (sizeof=" << sizeof(TYPE) << ")\n"; 
  else 
    std::cout << type_name << " is passed by value (sizeof=" << sizeof(TYPE) << ")\n"; 
}

int main()
{
  test<short>("short");
  test<int>("int");
  test<double>("double");
  test<std::string>("std::string");
  test<long long>("long long");
  test<std::pair<int, int>>("std::pair<int, int>");
  test<std::pair<short, short>>("std::pair<short, short>");
  test<std::pair<char, char>>("std::pair<char, char>");
  test<std::tuple<char, char>>("std::tuple<char, char>");
  test<std::tuple<char, char, char, char>>("std::tuple<char, char, char, char>");
  test<std::pair<long long, long long>>("std::pair<long long, long long>");
  return 0;
}

结果如下(Boost 1.50,g++ 4.7.2):

short is passed by value (sizeof=2)
int is passed by value (sizeof=4)
double is passed by value (sizeof=8)
std::string is passed by reference (sizeof=8)
long long is passed by value (sizeof=8)
std::pair<int, int> is passed by reference (sizeof=8)
std::pair<short, short> is passed by reference (sizeof=4)
std::pair<char, char> is passed by reference (sizeof=2)
std::tuple<char, char> is passed by reference (sizeof=2)
std::tuple<char, char, char, char> is passed by reference (sizeof=4)
std::pair<long long, long long> is passed by reference (sizeof=16)

最佳答案

Call Traits 是一个通用库,必须与任何用户定义的类型一起使用。决定按值传递任意类型是否更快需要额外的知识,这超出了库的范围。因此,在有疑问时始终按值传递的保守方法是合理的。

虽然应该可以扩展它以改进对常用 STL 类型的支持(例如,std::pairstd::tuple std::array),没有通用的方法来做到这一点。

关于c++ - 为什么 boost::call_traits 通过引用传递像 pair<char, char> 这样的小对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13215391/

相关文章:

java - Google AppEngine - Java - Slim3 - 在新 View 中显示对象(从 key 检索)属性

c - 如何允许可变参数传递给函数

c - 如何在 C 函数中传递二维数组(矩阵)?

c++ - Boost-graph:当我的图形使用listS作为VertexList时,如何调用depth-first-search()?

c++ - Boost Spirit : Error C2664, 无法将 'const boost::phoenix::actor<Eval>' 转换为 'char'

c++ - 制作结构数组?

android - unity : DllNotFoundException (Unity 2018. 2;安卓)

c++ - 如何重启 boost::timer::cpu_timer?

c++ - 找出 vptr 字段

c++ - 使用 '?' 打印特殊(扩展)ASCII 字符时在输出中获取 `std::cout`