gpt4 book ai didi

c++ - 可以通过 move 返回局部变量吗?

转载 作者:行者123 更新时间:2023-11-30 01:41:52 36 4
gpt4 key购买 nike

我正在阅读 Nicolai M. Josuttis 的 2nd edition of "The C++ Standard Library" covering C++11 ,其中第 18 章:并发,第 969 页和第 970 页给出了示例程序:

// concurrency/promise1.cpp
#include <thread>
#include <future>
#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
#include <functional>
#include <utility>
void doSomething (std::promise<std::string>& p)
{
try {
// read character and throw exceptiopn if ’x’
std::cout << "read char (’x’ for exception): ";
char c = std::cin.get();
if (c == ’x’) {
throw std::runtime_error(std::string("char ")+c+" read");
}
...
std::string s = std::string("char ") + c + " processed";
p.set_value(std::move(s)); // store result
}
catch (...) {
p.set_exception(std::current_exception()); // store exception
}
}

int main()
{
try {
// start thread using a promise to store the outcome
std::promise<std::string> p;
std::thread t(doSomething,std::ref(p));
t.detach();
...
// create a future to process the outcome
std::future<std::string> f(p.get_future());
// process the outcome
std::cout << "result: " << f.get() << std::endl;
}
catch (const std::exception& e) {
std::cerr << "EXCEPTION: " << e.what() << std::endl;
}
catch (...) {
std::cerr << "EXCEPTION " << std::endl;
}
}

这里的string s 是一个局部变量但是移到了return。

但是,随着程序逐级退出调用树,栈内存也会被释放。当调用堆栈展开时,这会成为问题吗?

注意:这个问题不同于c++11 Return value optimization or move? : 这个问题是关于 move is potentially dangerous,而另一个问题是关于是否主动禁止复制省略或让编译器决定。

最佳答案

Unless otherwise specified, all standard library objects that have been moved from are placed in a valid but unspecified state.有效意味着它可以安全地销毁(例如在堆栈展开时)。在您的示例中 s 未返回但存储在 promise 中,但如果以正常方式返回 return s; 编译器可以隐式调用 return move(s);.

关于c++ - 可以通过 move 返回局部变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40668902/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com