C ++ 11:移动语义是否涉及通过值? [英] C++11: Do move semantics get involved for pass by value?

查看:116
本文介绍了C ++ 11:移动语义是否涉及通过值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的API:

I've got an API that looks like this:

void WriteDefaultFileOutput(std::wostream &str, std::wstring target)
{
    //Some code that modifies target before printing it and such...
}

我想知道通过这样做是否明智地启用move语义:

I'm wondering if it'd be sensible to enable move semantics by doing this:

void WriteDefaultFileOutput(std::wostream &str, std::wstring&& target)
{
    //As above
}
void WriteDefaultFileOutput(std::wostream &str, std::wstring const& target)
{
    std::wstring tmp(target);
    WriteDefaultFileOutput(str, std::move(tmp));
}

或者这只是编译器应该能够找出的样板?

or is this just boilerplate that the compiler should be able to figure out anyway?

推荐答案

按值传递可以指复制或移动;如果参数是一个左值,则调用复制构造函数。如果参数是右值,则调用move构造函数。

"Pass by value" can mean either copy or move; if the argument is an lvalue, the copy constructor is invoked. If the argument is an rvalue, the move constructor is invoked. You don't have to do anything special involving rvalue references to get move semantics with pass by value.

我在有人可以向我解释移动语义吗?

这篇关于C ++ 11:移动语义是否涉及通过值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆