在 C++ 中,如何从方法返回一个参数,不改变,没有拷贝?
// This is more or less the desired signature from the caller's point of view
SomeImmutableObject ManipulateIfNecessary(SomeImmutableObject const& existingObject)
{
// Do some work…
// ...
if (manipulationIsNeccessary)
{
// Return a new object with new data etc (preferably without another copy)...
return SomeImmutableObject(...);
}
else
{
// Return the original object intact (but with no further copies!)...
return existingObject;
}
}
一个例子是 C# 的 String.Trim 方法。 C# 字符串是不可变的,如果 Trim 不需要做任何工作,则返回对现有字符串的引用,否则返回具有修剪内容的新字符串对象。
在给出接近上述方法签名的情况下,我如何在 C++ 中模仿这种语义?
最佳答案
您的对象必须是引用类型才能工作。让我们举一个字符串的玩具示例:
class RefString {
public:
RefString() : ref(new std::string()) { }
RefString(const std::string& str) : ref(new std::string(str)) { }
RefString trim_trailing_newline() {
if (ref->back() == '\n') {
return RefString(ref->substr(0, ref->size()-1));
}
return *this;
}
size_t size() { return ref->size(); }
private:
std::shared_ptr<std::string> ref;
};
int main(int argc, char** argv) {
RefString s("test\n");
std::cout << s.size() << "\n";
std::cout << s.trim_trailing_newline().size() << "\n";
return 0;
}
关于c++ - 在 C++ 中,如何从方法中返回一个不可变的参数,保持不变且没有拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026088/