auto_ptr
in BCB4 - strange goings on?
by Curtis Krauskopf
The BCB4 compiler gives a misleading error message
when it encounters a common auto_ptr problem.
Date: Wed, 26 May 1999 10:05:13 -0400
(copied and edited from a message posted on borland.public.cpp.language)
Q: Given the code:
#include <memory>
#pragma argsused
int main(int argc, char* argv[])
{
int* intptr;
std::auto_ptr<int> i;
i = std::auto_ptr<int> (intptr);
return 0;
}
I get the compile-time error:
|
|
|
|
"Could
not find a match for 'std::auto_ptr<int>::operator=(std::auto_ptr<int>)'". |
|
|
|
|
A: Your code should
NOT compile. The error message is leaving out a major
clue as to why. It should read
|
|
|
|
[C++ Error]
Project2.cpp(8): E2285 Could not find a match for
'std::auto_ptr<int>::operator =(std::auto_ptr<int>
const &)'. |
|
|
|
|
You are trying to assign a const reference to an auto_ptr,
but operator= for an auto pointer only takes
non-const operands. Remember, an unnamed temporary
object is const, according to ANSI. The reason
is that auto_ptr has exclusive ownership, and to assign
one pointer to another means that the original auto_ptr
no longer owns the memory... requiring the object to
be modified. You cannot do this on a const object.
The solution is to create a temporary auto_ptr that
has a name, (a local variable), and assign it to i.
The compiler is correctly flagging an error, but not
reporting it very clearly.
#include <memory>
#pragma argsused
int main(int argc, char* argv[])
{
int* intptr;
std::auto_ptr<int> i;
std::auto_ptr<int> temp(intptr); // temp is non-const
i = temp; // assignment ok
return 0;
}
Popular C++ topics at The Database Managers:
|