Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c++11 - C++ std::tuple order of destruction

Is there a rule which states in which order the members of an std::tuple are destroyed?

For example if Function1 returns an std::tuple<std::unique_ptr<ClassA>, std::unique_ptr<ClassB>> to Function2, then can I be sure that (when the scope of Function2 is left) the instance of ClassB referred to by the second member is destroyed before the instance of ClassA referred to by the first member?

std::tuple< std::unique_ptr< ClassA >, std::unique_ptr< ClassB > > Function1()
{
    std::tuple< std::unique_ptr< ClassA >, std::unique_ptr< ClassB > > garbage;
    get<0>(garbage).reset( /* ... */ );
    get<1>(garbage).reset( /* ... */ );
    return garbage;
}

void Function2()
{
    auto to_be_destroyed = Function1();
    // ... do something else

    // to_be_destroyed leaves scope
    // Is the instance of ClassB destroyed before the instance of ClassA?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll offer a life lesson I've learned, rather than a direct answer, in response to your question:

If you can formulate, for multiple alternatives, a reasonable argument for why that alternative should be the one mandated by the standard - then you should not assume any of them is mandated (even if one of them happens to be).

In the context of tuples - please, please be kind to the people maintaining your code and do not allow the destruction order of tuple elements to potentially mess up the destruction of other elements. That's just evil... imagine the hapless programmer who will need to debug this thing. In fact, that poor soul might be yourself in a few years, when you've already forgotten about your clever trick from back-in-the-day.

If you absolutely must rely on destruction order, perhaps you should just be using a proper class with the tuple's elements as its data members (which you could write a destructor for, making it clear what needs to happen in what order), or some other arrangement facilitating a more explicit control of the destruction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...