AUTOSAR C++14 Rule A18-1-3
Description
Rule Definition
The std::auto_ptr shall not be used.
Rationale
The std::auto_ptr
is a type of class template that predates the
introduction of move semantics in the C++11 language standard. When you copy a source
std::auto_ptr
object into a target object, the source object is
modified. The compiler transfers the ownership of the resources in the source object to the
target object and sets the source object to a null-pointer. Because of this unusual copy
syntax, using the source object after the copy operation might lead to unexpected behavior.
Consider this code snippet where the use of std::auto_ptr
results in a
segmentation fault.
void func(auto_ptr<int> p) { cout<<*p; //... } int main() { std::auto_ptr<int> s = new int(1); //.. func(s); // This call makes s a null-pointer //... func(s); // exception, because s is null return 1; }
The first call to func()
copies the source
std::auto_ptr
object s
to the argument
p
, transfers ownership of the pointer to p
, and sets
s
to a null pointer. When func()
is called again,
the compiler tries to access the null-pointer s
, causing a segmentation
fault.
The std::auto_ptr
type objects are also incompatible with any generic
code that expects a copy operation to not invalidate the source object, such as the standard
template library (STL). Avoid using std::auto_ptr
. It is deprecated in
C++11 and removed from C++17. The C++11 language standard introduces
std::unique_ptr
as a safer replacement for
std::auto_ptr
. Use std::unique_ptr
instead of
std::auto_ptr
.
Polyspace Implementation
Polyspace® flags all instances of std::auto_ptr
in your code, other
than those in C style arrays.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Language support library |
Category: Required, Automated |
Version History
Introduced in R2020a