相关疑难解决方法(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万
查看次数

是应该通过函数的值还是通过"std :: string&s"作为参数返回std :: string?

为了从函数中返回一个字符串,这两个中的哪一个更有效(即我应该使用哪一个):

std::string f(const std::string& s)
{
    return s + "some text";
}
Run Code Online (Sandbox Code Playgroud)

要么

void f(const std::string& s, std::string &result)
{
    result = s + "some text";
}
Run Code Online (Sandbox Code Playgroud)

我明白答案可能取决于特定的编译器.但我想知道现代C++代码中推荐的方法(如果有的话)是什么.

根据下面的"轨道轻度竞赛"评论,这里是我问到这个问题之前在stackoverflow上找到的一些相关问题:

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

通过Value或Reference传递std :: string

通过值或const引用?

"std :: string"或"const std :: string&"参数?(该参数在内部复制和修改)

这些都没有回答我关于从函数返回值而不是将字符串作为额外参数返回的特定问题.

c++ string performance c++11

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

无法在C++代码中调试字符串转换事物

我是C++ OOP概念的新手.我目前在getter和setter函数中使用字符串声明的问题.我使用eclipse IDE,我得到的错误是

error: cannot convert 'Student::getname' from type 'std::__cxx11::string (Student::)() {aka std::__cxx11::basic_string<char> (Student::)()}' to type 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}'
return getname;

代码如下:

#include<iostream>
#include<string.h>
using namespace std;

class Student
{
private:
    int rollno;
    string name;
    string school;
public:

void setrollno(int i)
{
    rollno =i;
}
void setname(string n)
{
    name =n;
}
void setschool(string s)
{
    school =s;
}
int getrollno()
    {
        return rollno;
    }
string getname()
{
    return getname;
}
string getschool()
{
    return school;
}
};
int main() …
Run Code Online (Sandbox Code Playgroud)

c++ string c++11

0
推荐指数
1
解决办法
120
查看次数

标签 统计

c++ ×3

c++11 ×3

string ×2

performance ×1