Hi CornedBee,
I am trying to implement your ideas. But there is some strange compile error for the following code. Anything wrong with my code?
1>main.cpp
1>d:\program files\microsoft visual studio 9.0\vc\include\vector(1209) : error C2558: class 'std::auto_ptr<_Ty>' : no copy constructor available or copy constructor is declared 'explicit'
1> with
1> [
1> _Ty=int
1> ]
1> d:\program files\microsoft visual studio 9.0\vc\include\vector(1158) : while compiling class template member function 'void std::vector<_Ty>::_Insert_n(std::_Vector_const_ite rator<_Ty,_Alloc>,unsigned int,const _Ty &)'
1> with
1> [
1> _Ty=std::auto_ptr<int>,
1> _Alloc=std::allocator<std::auto_ptr<int>>
1> ]
1> d:\visual studio 2008\projects\test_autoptr1\test_autoptr1\main.cpp (16) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1> with
1> [
1> _Ty=std::auto_ptr<int>
1> ]
1>d:\program files\microsoft visual studio 9.0\vc\include\vector(1233) : error C2558: class 'std::auto_ptr<_Ty>' : no copy constructor available or copy constructor is declared 'explicit'
1> with
1> [
1> _Ty=int
1> ]
Code:
#include <memory>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool foosort (auto_ptr<int> lhs, auto_ptr<int> rhs)
{
return *lhs < *rhs;
}
int main( )
{
int i = 0;
vector<auto_ptr<int>> vc;
for (i = 0; i < 5; i ++) // 0 1 2 3 4
{
auto_ptr<int> pi (new int(i));
vc.push_back (pi);
}
for (i = 10; i > 5; i--) // 10 9 8 7 6
{
auto_ptr<int> pi (new int(i));
vc.push_back (pi);
}
sort (vc.begin(), vc.end(), foosort);
return 0;
}
Originally Posted by
CornedBee
Both.
The reason auto_ptr cannot be stored in containers is more complex than what cpjust said. But let's leave it at saying that auto_ptr does not have normal copy semantics, and that some operations on containers assume normal copy semantics.
If you want to see an experiment, create a std::vector<std::auto_ptr<int> >, put some values in it, and then call std::sort() on the thing (use a dereferencing predicate, i.e.
Code:
struct deref_less
{
template<typename T>
bool operator ()(const T &lhs, const T &rhs) {
return *lhs < *rhs;
}
};
). Observe the pointers after the sort operation.
That is, provided that your standard library isn't smart enough to prevent compilation of the thing in the first place.
regards,
George