我试图理解rvalue引用并移动C++ 11的语义.
这些示例之间有什么区别,哪些不会执行矢量复制?
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return tmp;
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud)
std::vector<int>&& return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud)
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
Run Code Online (Sandbox Code Playgroud) 请考虑此代码.我已经多次看过这种类型的代码了.words是一个本地向量.如何从函数中返回它?我们可以保证它不会死吗?
std::vector<std::string> read_file(const std::string& path)
{
std::ifstream file("E:\\names.txt");
if (!file.is_open())
{
std::cerr << "Unable to open file" << "\n";
std::exit(-1);
}
std::vector<string> words;//this vector will be returned
std::string token;
while (std::getline(file, token, ','))
{
words.push_back(token);
}
return words;
}
Run Code Online (Sandbox Code Playgroud) 这是我使用C ++并进行学习的第一年。我目前正在阅读“返回值优化”(我使用C ++ 11 btw)。例如在这里https://en.wikipedia.org/wiki/Return_value_optimization,立即想到这些具有原始类型的初学者示例:
int& func1()
{
int i = 1;
return i;
}
//error, 'i' was declared with automatic storage (in practice on the stack(?))
//and is undefined by the time function returns
Run Code Online (Sandbox Code Playgroud)
...还有这个:
int func1()
{
int i = 1;
return i;
}
//perfectly fine, 'i' is copied... (to previous stack frame... right?)
Run Code Online (Sandbox Code Playgroud)
现在,我开始尝试根据另外两个方面来理解它:
Simpleclass func1()
{
return Simpleclass();
}
Run Code Online (Sandbox Code Playgroud)
这里实际发生了什么?编辑:我知道大多数编译器将优化此,我问的不是'if',而是:
非常感谢,