【发布时间】:2014-10-17 07:10:08
【问题描述】:
我有一个班级说,
class Foo
{
public:
void ProcessString(std::string &buffer)
{
// perform operations on std::string
// call other functions within class
// which use same std::string string
}
void Bar(std::string &buffer)
{
// perform other operations on "std::string" buffer
}
void Baz(std::string &buffer)
{
// perform other operations on "std::string" buffer
}
};
此类尝试使用std::string 缓冲区在这些条件下使用各种方法对其执行操作:
- 我不想传递我已经拥有的
std::string的副本。 - 我不想创建此类的多个对象。
例如:
// Once an object is created
Foo myObject;
// We could pass many different std::string's to same method without copying
std::string s1, s2, s3;
myObject.ProcessString(s1);
myObject.ProcessString(s2);
myObject.ProcessString(s3);
我可以使用该字符串并将其分配为类成员,以便其他使用的函数可以知道它。
但似乎我们不能有引用类成员std::string &buffer,因为它只能从构造函数初始化。
我可以使用指向std::string 的指针,即std::string *buffer 并将其用作类成员,然后传递s1, s2, s3 的地址。
class Foo
{
public:
void ProcessString(std::string *buf)
{
// Save pointer
buffer = buf;
// perform operations on std::string
// call other functions within class
// which use same std::string string
}
void Bar()
{
// perform other operations on "std::string" buffer
}
void Baz()
{
// perform other operations on "std::string" buffer
}
private:
std::string *buffer;
};
或者,另一种方法是向每个函数传递对std::string 缓冲区的引用,就像在上面的第一个示例中所示。
这两种方法看起来有点难看,因为我很少看到使用 std::string 作为指针或将类的所有函数传递给相同的参数。
有没有更好的解决方法或者我正在做的事情还不错?
【问题讨论】:
-
您已经在使用字符串而不进行复制。您通过引用传递,即 std::string &s.
-
您可能不应该过多担心字符串复制。它有什么问题?而且我不明白为什么你不只是通过引用
Bar和Baz来传递字符串。 -
@ChristianHackl 问题主要出在性能上,复制一个对象在 CPU 和内存方面都是昂贵的,而且事实上你不能在调用者中修改一个对象 [不完全替换它],除非你通过它指针或引用。
-
先生,我在菜鸟时代已经复制了足够多的字符串,知道它确实会导致性能下降,严重程度取决于您使用字符串的密集程度。我知道我在说什么。
-
我希望现在更清楚了。
标签: c++ string stl parameter-passing pass-by-reference