小编Rog*_*r B的帖子

如何从方法中返回不可变参数,未更改,并且在c ++中没有副本?

如何从方法中返回参数,未更改,并且没有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++中模仿这种语义?

c++ immutability

6
推荐指数
1
解决办法
153
查看次数

标签 统计

c++ ×1

immutability ×1