Main Content

AUTOSAR C++14 Rule A18-1-3

The std::auto_ptr shall not be used

Since R2020a

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

expand all

This code shows how Polyspace flags std::auto_ptr in your code.

#include <cstdint>
#include <memory>
#include <vector>
#define AUTOPTROF(_TYPE) std::auto_ptr<_TYPE>
AUTOPTROF(int) v_int;                           // Noncompliant
typedef struct {
	std::auto_ptr<bool> vb;                     // Noncompliant
} T;
T vec; 
typedef std::auto_ptr<int> my_int_auto_ptr;     // Noncompliant
void Fn() noexcept
{
      
	std::auto_ptr<std::int32_t> ptr1(new std::int32_t(10)); // Noncompliant
	std::unique_ptr<std::int32_t> ptr2 =
	std::make_unique<std::int32_t>(10);         // Compliant
	std::vector<std::auto_ptr<std::int32_t>> v;  // Noncompliant
}

int main(){
	//..
}

Polyspace flags the std::auto_ptr objects. Use std::unique_ptr instead of std::auto_ptr.

Check Information

Group: Language support library
Category: Required, Automated

Version History

Introduced in R2020a