繁体   English   中英

如何优化右值参数的返回值避免复制

[英]How to optimize the return value of rvalue parameter to avoid copy

我正在写一个网络模块,使用的包络model,下面是一个发送的function,function参数使用右值参考:

Envelope NatsTransport::Send(Envelope&& envelope)
{
    // do somthing...

    if (!natsConnection->Send(envelope.GetContent(), envelope.Length()))
    {
        return envelope.With<SentFaildStamp>("envelope send faild");
    }

    return envelope; // called the envelope's copy constructor
    // return std::move(envelope); // called the envelope's copy constructor
}
template <class TStamp, typename... Args>
Envelope With(Args&&... args) const 
{
     // When the With method is called, the copy constructor of the
     // envelope is called. This is in line with the design expectations,
     // because adding stamps to the envelope will not modify the old envelope.
     return With(std::make_shared<TStamp>(std::forward<Args>(args)...));
}

但是我发现它在返回时调用了信封的复制构造函数。

有没有办法避免调用复制构造函数并使用移动语义?

我使用调试模式进行断点跟踪,找到了复制构造函数的调用。


注意:我尝试实现移动构造函数,但在返回值时似乎不起作用。

class Envelope final 
{
public:
    Envelope::Envelope(const Envelope& other) 
    {
        offset_ = other.offset_;
        length_ = other.length_;
        content_ = other.content_;
        stamps_ = other.stamps_;
    }
   
    Envelope(Envelope&& other)
    {
        offset_ = other.offset_;
        length_ = other.length_;
        content_ = std::move(other.content_);
        stamps_ = std::move(other.stamps_);
    }

    Envelope& operator=(const Envelope& other) noexcept
    {
       if (this == &other)
       {
           return *this;
       }

       offset_ = other.offset_;
       length_ = other.length_;
       content_ = other.content_;
       stamps_ = other.stamps_;

       return *this;
    }

    Envelope& operator=(Envelope&& other) noexcept
    {
        if (this == &other)
        {
            return *this;
        }

        offset_ = other.offset_;
        length_ = other.length_;
        content_ = std::move(other.content_);
        stamps_ = std::move(other.stamps_);

        return *this;
    }

private:
    size_t offset_ = 0;
    size_t length_ = -1;
    std::shared_ptr<const void> content_ = nullptr;
    std::map<std::string, std::vector<std::shared_ptr<StampInterface>>> stamps_;
}

移动 const 对象(如您的原始帖子中所示)选择常规复制构造函数而不是移动构造函数。

您将需要Envelope(const Envelope&&)实际上很少使用。

当参数不是 const

return std::move(envelope)应该调用移动构造函数(如果可用)。

return envelope调用复制构造函数。 如果envelope是局部变量,则在某些情况下会调用 move ,但这不是您的情况(这里是(右值)引用)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM