我正在写一个网络模块,使用的是信封模型,下面是一个sent函数,函数参数使用的是右值引用?
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
}
Run Code Online (Sandbox Code Playgroud)
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)...));
}
Run Code Online (Sandbox Code Playgroud)
但是我发现它在返回时调用了信封的复制构造函数。
有没有办法避免调用复制构造函数并使用移动语义?
我使用调试模式进行断点跟踪,发现了复制构造函数的调用。
注意:我尝试实现移动构造函数,但在返回值时它似乎不起作用。
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_;
}
Run Code Online (Sandbox Code Playgroud)
移动 const 对象(如在您的原始帖子中)选择常规复制构造函数而不是移动构造函数。
你会需要Envelope(const Envelope&&)它实际上很少使用。
当参数不是 const 时
return std::move(envelope) 应该调用移动构造函数(如果可用)。
return envelope调用复制构造函数。在某些情况下, move 被调用,如果envelope是局部变量,但不是你的情况(这里是(右值)引用)。
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |