Here is my code:
class Mystring
{
private:
unsigned int size;
shared_ptr<char>message=make_shared<char>();
public:
Mystring(const char* input):size(strlen(input)),message(make_shared<char>(size+1))
{cout<<"Created"<<endl;memcpy(this->message,input,size+1);}
Mystring(const Mystring& other):size(other.size),message(make_shared<char>(size+1))
{cout<<"Created"<<endl;memcpy(this->message,other.message,size+1);}
~Mystring(){cout<<"Deleted"<<endl;}
friend ostream& operator<<(ostream& Cout,const Mystring& mystring)
{Cout<<mystring.message<<endl;return Cout;}
char& operator[](const unsigned int index)
{return this->message[index];}
};
I want to use smart pointers and operator []
properly. How can I solve these problems:
no suitable conversion function from "std::shared_ptr<char>" to "void *" exists no operator "[]" matches these operands
So lots of problems with this code
You have a shared char array, so the type is shared_ptr<char[]>
not shared_ptr<char>
. This also means you cannot use make_shared
, since it doesn't work with arrays.
If you want to access the pointer to the array use get()
.
Your copy constructor allocates a new array, which is a bit weird since why are you using shared_ptr
, if you don't want to share the array? On the other hand the default assignment operator will share the array, so you have a strange situation where sometimes when you copy Mystring
you will share the array, and sometimes you won't.
Various other minor issues
Here's a version that works
class Mystring
{
private:
size_t size;
shared_ptr<char[]> message;
public:
Mystring(const char* input) : size(strlen(input)), message(new char[size+1])
{
cout<<"Created"<<endl;
memcpy(message.get(), input, size+1);
}
Mystring(const Mystring& other): size(other.size), message(other.message)
{
cout<<"Created"<<endl;
}
~Mystring()
{
cout<<"Deleted"<<endl;
}
friend ostream& operator<<(ostream& Cout,const Mystring& mystring)
{
Cout<<mystring.message.get()<<endl;return Cout;
}
char& operator[](size_t index)
{
return message.get()[index];
}
};
I changed the copy constructor so that it does share the underlying array. You can change it back if you wish. However is you want a Mystring
which does not share it's array with other Mystring
objects then it would make more sense to use unique_ptr<char[]>
instead of shared_ptr
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.