C ++ lvalue,rvalues,引用,参数和性能 [英] C++ lvalues, rvalues, references, parameters, and performance

查看:151
本文介绍了C ++ lvalue,rvalues,引用,参数和性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个函数,需要一个std :: vector作为参数。我想知道最好的声明参数的方法,使底层数组不被深度复制,因为它可能相当大。

So I have a function that needs to take an std::vector as a parameter. I'd like to know the best way to declare the parameter so that the underlying array is not deep-copied, as it could be rather large.

// which should I choose?
void myFunc(std::vector<char>); // 1
void myFunc(std::vector<char>&); // 2
void myFunc(std::vector<char>&&);  // 3
void myFunc(std::vector<char>*) // 4

我应该选择哪一个?另外,我不会在函数中修改向量,所以我不应该添加const?

Which should I choose? Also, I won't be modifying the vector in the function so shouldn't I add const? Should I overload the function and have a combination of these?

推荐答案


  1. 如果你是将在函数中复制它:

  1. If you are going to make a copy of it inside the function anyway:

void myFunc(std::vector<char>);


  • 如果您只是想读取参数而不复制它:

  • If you just want to read the argument without copying it:

    void myFunc(const std::vector<char>&);
    


  • 如果要修改传递给函数的原始向量:

  • If you want to modify the original vector passed to the function:

    void myFunc(std::vector<char>&);
    


  • 如果您想要优化右值将参数 移动 到函数中:

  • If you want to optimize for rvalues or if you want to move the argument into the function:

    void myFunc(std::vector<char>&&);
    


  • 如果您需要能够表示通过引用传递的可选参数:

  • If you need to be able to signify an optional argument passed by reference:

    void myFunc(const std::vector<char>*);
    


  • 如果您需要传递一个可选参数, c $ c> nullptr :

    void myFunc(std::vector<char>*);
    


  • 这篇关于C ++ lvalue,rvalues,引用,参数和性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆