相关疑难解决方法(0)

将const std :: string&作为参数传递的日子是多少?

我听取了香草萨特最近的谈话谁建议的理由来传递std::vectorstd::string利用const &在很大程度上消失了.他建议现在更好地编写如下函数:

std::string do_something ( std::string inval )
{
   std::string return_val;
   // ... do stuff ...
   return return_val;
}
Run Code Online (Sandbox Code Playgroud)

我理解return_val在函数返回时将是一个rvalue,因此可以使用非常便宜的移动语义返回.但是,inval仍然远大于引用的大小(通常实现为指针).这是因为a std::string具有各种组件,包括指向堆的指针和char[]用于短字符串优化的成员.所以在我看来,通过引用传递仍然是一个好主意.

谁能解释为什么Herb可能会说这个?

c++ c++11

579
推荐指数
11
解决办法
17万
查看次数

通过Value或Reference传递std :: string

可能重复:
传递const std :: string&作为参数的日期是多少?

如果std::string支持移动语义,我应该通过值传递还是通过引用传递(到非内联函数)?那么使用小字符串优化(SSO)的实现呢?

c++ string std move-semantics

72
推荐指数
3
解决办法
11万
查看次数

通过值或const引用?

一组很好的规则来确定是否通过值或const引用传递

  • 如果函数打算将参数更改为副作用,请使用非const引用.
  • 如果函数不修改其参数且参数是基本类型,则按值取值.
  • 否则通过const引用获取它,除非在下列情况下:如果函数需要复制const引用,请按值取值.

对于构造函数如下,如何确定它?

class A
{
public:
    A(string str) : mStr(str) {} // here which is better, 
                                 // pass by value or const reference?

    void setString(string str)  { mStr = str; } // how about here?

private:
    string mStr;
};
Run Code Online (Sandbox Code Playgroud)

c++ parameter-passing

7
推荐指数
1
解决办法
3892
查看次数

标签 统计

c++ ×3

c++11 ×1

move-semantics ×1

parameter-passing ×1

std ×1

string ×1