It is not possible to return the added item or container as a member function of the container in safe mode. STL containers basically provide a “strong guarantee." The return of the managed item or container will make it impossible to provide a reliable guarantee (this will provide only a “basic guarantee”). An explanation of these conditions is provided on the boost website for Exception-Security in Common Components . See below the Boost website .
- Basic guarantee: preservation of component invariants and resource leakage.
- Strong guarantee: the operation completed successfully or threw an exception, leaving the state of the program exactly as it was before the start of the operation.
- Throw-Free Prevention: The operation will not throw an exception.
Back to the topic: In this previous SO answer , the reason is that returning something could cause a constructor call that might throw an exception, But the function has already exited, so it successfully completed its main task, but still threw an exception. which is a violation of a strong guarantee. You may be thinking, "Well, then we will return by reference!" Although this sounds like a good solution, it is not entirely safe. Consider the following example:
MyClass bar = myvector.push_back(functionReturningMyClass());
However, if the copy-assignment operator throws, we do not know whether push_back succeeded or not, indirectly violating the strong guarantee. Although this is not a direct violation. Of course, using MyClass& bar = //... instead would fix this problem, but it would be rather inconvenient for the container to get into an undefined state, just because someone forgot &.
A similar argument is that std::stack::pop() does not return a pop-up value. Instead, top( ) returns the highest value in a safe way. after calling top, even when a copy constructor or copy assignment constructor is created, you still know that the stack has not changed.
user195488
source share