c++ - 局部自动函数变量的销毁与返回值的构造之间的顺序

标签 c++ c++11 c++14 language-lawyer c++17

存在依赖于本地自动函数变量在创建返回值后销毁的代码,例如:

1) Unmangling the result of std::type_info::name

std::string demangle(const char* name)
{
    int status = -4;
    std::unique_ptr<char, void(*)(void*)> res {
        abi::__cxa_demangle(name, NULL, NULL, &status),
        std::free
    };
    return (status==0) ? res.get() : name;
}

2) Timing of scope-based lock guards and return values

class C {
    mutable std::mutex _lock;
    map<string,string> deep_member;
public:
    auto get_big_lump()
    {
        std::unique_lock<std::mutex> lock(_lock);
        return deep_member;
    }
};

标准在哪里规定这个顺序是有保证的?

最佳答案

[stmt.return]/3 :

The copy-initialization of the result of the call is sequenced before the destruction of temporaries at the end of the full-expression established by the operand of the return statement, which, in turn, is sequenced before the destruction of local variables ([stmt.jump]) of the block enclosing the return statement.

关于c++ - 局部自动函数变量的销毁与返回值的构造之间的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998516/

相关文章:

c++ - 为什么在 C++14 中不推荐使用 std::shuffle 方法?

c++ - C++中跨多个文件的类

c++ - 对 "non-type"模板参数执行规则

c++ - 如何将参数的数组初始值设定项迁移到 C++11 中的可变模板参数

c++ - 我可以使用 reinterpret_cast 将指向成员函数的指针转换为 char 数组并返回吗?

c++ - C++ 对象没有得到 std::moved 吗?

c++ - 链接器错误 : DLL and inheritance

c++ - 使用 swprintf() 打印 "0x0"的格式字符串应该是什么?

c++ - 用右值初始化左值引用

c++ - 在 std::find 中使用来自不同命名空间的运算符