For this error:
error C2440: 'delete' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'void *'
You don't need to delete an instant of shared_ptr. The shared_ptr would hold the resource (the new data
) with a reference counter, and delete it automatically when the reference counter is 0, meaning that the resource was not used at all. See the manual of shared_ptr for detail
smart pointer in the std::map
-
10-03-2022 - |
سؤال
I've defined a class myClass
,one of its data members is
std::map<int,data*> dataMap
data is defined as
struct data
{
int d1;
int d2;
std::string d3;
}
Inserting of data to the dataMap is done as follows :dataMap[key] = new data;
the following assignment causes a problem:
myClass a1,a2;
//init a1;
a2 = a1;
I want to use auto_ptr for data instead of data*.how do i do that?-
since there are a problem with destructing "bad pointers for data of a1" after a2 is destructed.std::map<int,std::auto_ptr<data> >
is problematic to compile
Upd As you advised I use std::shared_ptr but it still causes a problems :
in VS10
error C2440: 'delete' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'void *'
1> with
1> [
1> _Ty=data
1> ]
Can you write sample code pointing the correct way to use shared_ptr
المحلول 2
نصائح أخرى
Using auto_ptr
is a bad idea (it is deprecated) in general and even worse when combined with standard containers.
Prefer the better designed std::shared_ptr
or std::unique_ptr
(depending on your situation) and your code will work with one exception: You need to construct the correct smart pointer type when trying to insert it into the container, as the smart pointers are not implicitly constructible from raw pointers.
std::auto_ptr
is not safe to be used in containers, that why it's been deprecated. Use std::shared_ptr
or boost::shared_ptr
if available.
You could also use std::unique_ptr
if appropriate and available, but it is a bit trickier.
You can use either std::unique_ptr
in C++11 if you have a unique ownership (ie, the object will never be shared and only the creator can destruct it again) or you can use std::shared_ptr
if you will have shared ownership.
If you're using C++03 you can use boost::shared_ptr
or boost::unique_ptr
instead.