A class containing auto_ptr stored in a vector

In response to Is it safe to store class objects with std :: auto_ptr as its member variable in std :: vector? I stated that a class containing auto_ptr can be stored in a vector if the class has a custom copy constructor .

There were several comments suggesting that this was not the case, so this question is an attempt to fix the problem. Consider the following code:

#include <memory>
#include <vector>
using namespace std;

struct Z {};

struct A {

    A( Z z ) 
        : p( new Z(z) ) {} 

    A( const A & a ) 
        : p( a.p.get() ? new Z( *a.p.get()) : 0 ) {}

    // no assigment op or dtor defined by intent

    auto_ptr <Z> p;
};

int main() {
    vector <A> av;              
    Z z;                    
    A a(z);
    av.push_back( a );      
    av.push_back( A(z) );   
    av.clear();             
}                           

Please read the above and indicate in your answer where undefined behavior in the meaning of the C ++ standard can take place for this particular class used in this way. I don't care if the class is useful, whether it is well executed, sorted, or how it runs on exceptions.

, auto_ptrs. , .

, , , . , ctor . ( !) . ( Earwicker)

+3
5

, undefined.

#include <memory>
#include <vector>
using namespace std;

struct Z {};

struct A {

    A( Z z ) 
        : p( new Z(z) ) {} 

    A( const A & a ) 
        : p( a.p.get() ? new Z( *a.p.get()) : 0 ) {}

    // no assigment op or dtor defined by intent

    auto_ptr <Z> p;
};

int main() {
    vector <A> av;  
    ...
}

, A.

23.1/3:

, , CopyConstructible (20.1.3) Assignable types.

23.1/4 ( ):

64 T - , , t - T, u - (, const) T.

+-----------+---------------+---------------------+
|expression |return type    |postcondition        |
+-----------+---------------+---------------------+
|t = u      |T&             |t is equivalent to u |
+-----------+---------------+---------------------+

64

12.8/10:

, . X

X& X::operator=(const X&)

  • B X , const B &, const volatile B & B,
  • X, M ( ), , const M &, const volatile M & M.

X& X::operator=(X&)

( )

17.4.3.6/1 and /2:

( , , , ) ++ , ++. , .

, undefined :

  • , , (20.1.5, 23.1, 24.1, 26.1). , , .

, auto_ptr, , , auto_ptr. , . , , , , , undefined.

+3

, , "CopyConstructable", "Assignable" (++ 2008 23.1/3).

CopyConstructable ( , ), , , , , ), . (++ 2008 23.1/4), , t - t, u - (, const) t:

t = u a T&, t u

(20.4.5/3): "auto_ptr CopyConstructible Assignable , , auto_ptr undefined.

, , auto_ptr, t u, , ' t "const T u" ( , " - (-) ).

+4

, , . , std::vector const A&?

, Visual Studio ++ 2008 1:

binary '=': , 'const A' ( )

, , Herb Sutter, V++ , , , auto_ptr . , , , , , , , , , .

g++ 3.4.5, .

+3

auto_ptr , , boost::scoped_ptr. , .

0

?

cout << av[ 0 ] << endl;

, , , . .

( , g++ -pedantic ... Comeau, VS2005.)

0

Source: https://habr.com/ru/post/1705636/


All Articles