移动语义是否涉及通过值

移动语义是否涉及通过值

本文介绍了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:移动语义是否涉及通过值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:43