如何从方法中返回参数,未更改,并且没有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;
}
}
Run Code Online (Sandbox Code Playgroud)
一个例子是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;
}
Run Code Online (Sandbox Code Playgroud)