I’m having trouble using std::auto_ptr. I try to compile the following on Ubuntu 11.10 using GCC 4.6.1, and I get the error message error: no match for call to ‘(std::auto_ptr<int>) (int*)’.
#include <memory>
#include <iostream>
class Toy {
public:
std::auto_ptr<int> foo;
Toy() {
foo(new int(3));
}
};
int main() {
Toy toy;
std::cout << *toy.foo << std::endl;
return 0;
}
I was pretty sure a std::auto_ptr< T > takes in a T* as its constructor arguments, but apparently not… My apologies if this is a trivial or duplicate question, but I searched the archives, and haven’t found an answer. Places like this seem to suggest that the above code should work. Anyway, any help would be appreciated!
To initialize the fields of a class you use the initialization list syntax:
otherwise, you may get a default-initialized
lineand reseat it with itsresetmethod:But there are more problems with this code; first of all,
new int(3)does not create an array of threeints (as I think you think), but it creates a singleintinitialized to3. What you probably meant wasnew int[3].But:
new int[3]would need adelete[]to be freed, butauto_ptruses plaindelete, i.e. it’s not intended to manage arrays. This because the solution provided by the standard library to manage arrays isstd::vector, which you should probably use instead of your homebrew solution, sincestd::vectorhas virtually no overhead over a “normal” dynamic array.