mardi 6 janvier 2015

Trying to implement a correct c++11 rawstring class

I'm trying to implement a rawstring class conform to c++11. Here is my code.



#include <iostream>
#include <string>
#include <memory>

class RawString
{
private:
char* buff_;
public:
RawString()
{
std::cout << "rawstring def ctor\n";
buff_ = nullptr;
}
~RawString()
{
delete [] buff_;
}
RawString(const char* str) {
std::cout << "rawstring normal char* ctor\n";
buff_ = new char[strlen(str) + 1];
strcpy(buff_, str);
buff_[strlen(str)] = '\0';
}
RawString(const RawString& str) : RawString(str.buff_) {
std::cout << "rawstring copy ctor\n";
}
RawString(RawString&& other) {
std::cout << "rawstring move ctor\n";
buff_ = other.buff_;
other.buff_ = nullptr;
}
RawString(char*&& other) {
std::cout << "rawstring move ctor\n";
buff_ = other;
other = nullptr;
}
void swap(RawString& other) {
std::swap(other.buff_, buff_);
}
// RawString& operator=(const char* str) {
// std::cout << "operator=char*\n";
// buff_ = new char[strlen(str) + 1];
// strcpy(buff_, str);
// buff_[strlen(str)] = '\0';
// return *this;
// }
RawString& operator=(RawString other) {
std::cout << "opeartor=\n";
swap(other);
return *this;
}
friend const RawString operator+(const RawString& lhs, const RawString& rhs) {
std::cout << "friend opt+\n";
char* buff = new char[strlen(lhs.buff_) + strlen(rhs.buff_) + 1];
strcpy(buff, lhs.buff_);
strcat(buff, rhs.buff_);
buff[strlen(lhs.buff_) + strlen(rhs.buff_)] = '\0';
return std::move(buff);
// RawString newStr(buff);
// delete[] buff;
// return newStr;
}
};

int main()
{
RawString str1("how are you");
RawString str2(str1);
RawString str3 = str1;
RawString str4;
str4 = str1;
str4 = "how are you";
RawString str5 = str1 + str2;
return 0;
}


I'm not sure whether my implementation is right. 0) Is my implementation correct?

1) Should swap be friend?

2) Should I implementate the RawString& operator=(const char* str) assignement operator?

3) Do I need to implment the char* move constructor?


Could give some suggestions?


Aucun commentaire:

Enregistrer un commentaire