Reputation: 103
I dont understand the error message that im getting and i have no idea how to fix that;
template<typename T>
class shared_pointer
{
private:
static int howManyObjects;
T* pointer;
public:
shared_pointer( T* p=nullptr)
{
pointer=p;
}
shared_pointer( shared_pointer& a)
{
a.pointer=this->pointer;
howManyObjects++;
}
~shared_pointer()
{
if(howManyObjects==1) delete pointer;
}
T& operator *()
{
return *pointer;
}
T* operator ->()
{
return pointer;
}
};
template<typename T>
int shared_pointer<T>::howManyObjects=0;
int main()
{
int b=5;
int* wsk=&b;
shared_pointer<int> a= shared_pointer<int>(wsk);
return 0;
}
error message:
main.cpp: In function ‘int main()’:
main.cpp:10:25: error: cannot bind non-const lvalue reference of type ‘shared_pointer<int>&’ to an rvalue of type ‘shared_pointer<int>’
shared_pointer<int> a= shared_pointer<int>(wsk);
In file included from main.cpp:2:0:
smartpp.cpp:14:2: note: initializing argument 1 of ‘shared_pointer<T>::shared_pointer(shared_pointer<T>&) [with T = int]’
shared_pointer( shared_pointer& a)
Upvotes: 1
Views: 101
Reputation: 3506
Your problem is in the copy constructor function:
shared_pointer( shared_pointer& a)
{
a.pointer = this->pointer;
howManyObjects++;
}
So, according to the space before the type of parameter a, you probably know that it's have to be a const by the copy constructor rules. But, when you tried to put there a const
you got the following error:
shared_pointer(const shared_pointer& a)
{
a.pointer = this->pointer; // Compilation error: assignment of member ‘shared_pointer<int>::pointer’ in read-only object
howManyObjects++;
}
So you tried to remove the const
and got the error you displayed in your post. The problem wasn't the const you tried to put there, but the assignment direction. You don't want to modify the parameter value, but the current object value. Change your copy constructor to the following and everything will be good:
shared_pointer(const shared_pointer& a)
{
this->pointer = a.pointer; // Pay attention that this get the value of a, and not the opposite.
howManyObjects++;
}
Upvotes: 1
Reputation: 7374
Define move assignment operator
shared_pointer& operator=(shared_pointer&& other)
{
pointer = other.pointer;
return *this;
}
there are a lot of things you are missing. I list some.
~shared_pointer()
doesn't decrease the reference count.
Because of this int* wsk=&b;
: your dtor
will delete a pointer in stack you SHOULD not do that.
howManyObjects
should not be static. It should also be changed atomically if you care about thread safety.
Upvotes: 0