それらがメモリで表現される場合、C++ オブジェクトは C 構造体と同じですか?
たとえば、C では、次のようなことができます。
struct myObj {
int myInt;
char myVarChar;
};
int main() {
myObj * testObj = (myObj *) malloc(sizeof(int)+5);
testObj->myInt = 3;
strcpy((char*)&testObj->myVarChar, "test");
printf("String: %s", (char *) &testObj->myVarChar);
}
+
C++ では組み込み型の演算子をオーバーロードできないと思いますchar *
。
だから私は余分なオーバーヘッドがない独自の軽量文字列クラスを作成したいと思いますstd::string
。std::string
連続して表されていると思います:
(int)length, (char[])data
まったく同じ機能が必要ですが、長さの前に付けることはありません (8 バイトのオーバーヘッドを節約できます)。
テストに使用しているコードは次のとおりですが、セグメンテーション違反が発生します
#include <iostream>
using namespace std;
class pString {
public:
char c;
pString * pString::operator=(const char *);
};
pString * pString::operator=(const char * buff) {
cout << "Address of this: " << (uint32_t) this << endl;
cout << "Address of this->c: " << (uint32_t) &this->c << endl;
realloc(this, strlen(buff)+1);
memcpy(this, buff, strlen(buff));
*(this+strlen(buff)) = '\0';
return this;
};
struct myObj {
int myInt;
char myVarChar;
};
int main() {
pString * myString = (pString *) malloc(sizeof(pString));
*myString = "testing";
cout << "'" << (char *) myString << "'";
}
編集:誰も私がやりたいことを本当に理解していません。はい、クラス内の文字列へのポインターを持つことができることはわかっていますが、それはプレーンな cstring よりも 8 バイト高価です。まったく同じ内部表現が必要でした。でも試してくれてありがとう
編集:私が達成したかったことの最終結果は、strcat などを使用する場合と比較して、追加のメモリ使用量なしで + 演算子を使用できることでした。
const char * operator+(const char * first, const char * second);