我有一堂课说
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
ie的指针,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用作指针或将类的所有函数传递给相同的参数,因此无法复制。
有没有更好的解决方案,或者我做的还好吗?
在MyObject中保留对象不拥有的字符串的引用或指针是危险的。容易得到讨厌的不确定行为。
看下面的法律示例(酒吧是公开的):
myObject.ProcessString(s1); // start with s1 and keep its address
myObject.Bar(); // works with s1 (using address previously stored)
查看以下UB:
if (is_today) {
myObject.ProcessString(string("Hello")); // uses an automatic temporary string
} // !! end of block: temporary is destroyed!
else {
string tmp = to_string(1234); // create a block variable
myObject.ProcessString(tmp); // call the main function
} // !! end of block: tmp is destroyed
myObject.Bar(); // expects to work with pointer, but in reality use an object that was already destroyed !! => UB
错误非常棘手,因为在读取函数的用法时,一切似乎都很好并且管理得当。自动销毁整组变量隐藏了该问题。
因此,如果您确实想避免复制字符串,则可以按照您的设想使用指针,但只能在ProcessString()直接调用的函数中使用此指针,并将这些函数设为私有。
在其他所有情况下,我强烈建议您重新考虑您的立场,并设想:
string&
在所有需要它的对象函数中使用参数。这避免了复制,但让调用者有责任组织适当的字符串管理。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句