Iterators on temporary container object

前端 未结 2 1621
萌比男神i
萌比男神i 2021-01-21 22:12

Suppose I have a function which returns a STL container by value, say std::list

std::list get_Foolist()
{
    std::list lst;
    //populate         


        
相关标签:
2条回答
  • 2021-01-21 22:15
    1. Which implementation is correct(as per standard)?

    Presumably all of them.

    1. Why it succeeds on all implementations other that VS?

    It is undefined behaviour because you are de-referencing invalidated iterators. So it can fail in an infinite number of ways. Or appear to work, which is a just another mode of failure.

    0 讨论(0)
  • 2021-01-21 22:26

    In C++ there are many philosophical design rules (some of which telling one the opposite of the other) but one that is very often applied is "trust the programmer".

    This rule allows the implementers to simply ignore mistakes on the programmer side: when you write code that does something wrong (like deleting an object twice, or iterating over a container that doesn't exist any more) the compiler is free to just ignore what would happen instead of raising a runtime error. This is what is called "undefined behavior".

    The rationale is that you will never do that and it's not worth wasting even just a nanosecond at runtime to check for those conditions to happen.

    If you get an immediate crash because the OS blocks an access outside your allocated virtual address space you can consider yourself extremely lucky.

    If you get a random value that shows crazy result you can still consider yourself lucky... unfortunately what happens sometimes is that you get an "reasonable" result anyway and this will hide the bug for long time because wrong code will do the "correct thing" and thus the programmer will move on to implement other features and adding more code on top of the wrong one.

    In other words "undefined behavior" means that anything can happen, including nothing.

    Normally what happens is that the code will fail only when the damage is high (i.e. when the code is in production and you are in a hurry with an angry customer).

    0 讨论(0)
提交回复
热议问题