按值或引用传递C ++字符串 [英] Passing C++ strings by value or by reference
问题描述
我想知道C ++字符串是否被认为小到足以比通过引用传递的值更有效。 p>否。通过引用传递:
void foo(const std :: string& pString);
一般来说,如果它们有一个非平凡的复制构造函数, -value。
字符串通常由指向数据的指针和长度计数器组成。
在模板代码中,你可以使用 const T&
,因为函数的定义将可用于编译器。这意味着它可以决定它是否应该作为参考。 (我想)
I'm wondering whether the C++ string is considered small enough to be more efficient when passed by value than by reference.
No. Pass it by reference:
void foo(const std::string& pString);
In general, pass things by-reference if they have a non-trivial copy-constructor, otherwise by-value.
A string usually consists of a pointer to data, and a length counter. It may contain more or less, since it's implementation defined, but it's highly unlikely your implementation only uses one pointer.
In template code, you may as well use const T&
, since the definition of the function will be available to the compiler. This means it can decide if it should be a reference or not for you. (I think)
这篇关于按值或引用传递C ++字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!