我刚刚开始使用C ++而我无法理解代码是如何工作的:
好的我分配内存,但在分配时没有人知道要分配的内存大小。但代码仍然有效。 分配了多少内存?编译器如何知道我需要多少内存?
编辑:
很抱歉,如果我的问题不明确。让我试着澄清一下。所以我通过使用指针在堆中动态分配一些内存。但由于sting变量中没有文本,我认为很难知道我将通过getline输入多少文本(字节)。
我试着询问两个不同文本文字的大小,是的,它们的大小不同。
sizeof("") // is 1 (because of the ending 0 maybe?)
sizeof("sometext") // is 9
但对于字符串:sizeof两次给我4次。很明显,sizeof()给出了指向字符串的指针的长度。
如何分配内存?如果我为新字符串分配内存,只分配给指向字符串中第一个字符的内存地址的指针? 显然,我输入的字符必须存储在某个地方。我首先分配内存,然后加载一些文本。
编辑2:使编辑过的代码看起来是代码,而不是纯文本。
//Edit:
string a,b = "sometext";
cout << sizeof(a) << endl; //4
cout << sizeof(b); //4
//--------------------------------------------------------
#include <iostream>
#include <string>
#include <exception>
using namespace std;
int main()
{
//Defining struct
struct musicCD
{
string artist, title; // artist of the CD
};
//Memory allocation
musicCD *ptr;
try{ptr = new musicCD;}
catch(bad_alloc){cerr << "Out of memory :(";return -1;}
catch(...){cerr << "Something bad happened :O !";return -1;
}
//Get the data to store:
cout << "Please enter the data for the CD!' " << endl;
cout << "Please enter the artist: ";getline(cin, ptr->artist); cout << endl;
//Write out the data
cout << "The data entered: " << endl;
cout << "The artist performing is: \t" << ptr->artist << endl;
delete ptr;
return 0;
}
答案 0 :(得分:2)
您似乎对std::string
或任何动态容器如何处理内存需求未预先确定的事实感到困惑。 std::string
例如不在内部存储它的字符数据。简单地说,它包含一个指向另一个动态分配缓冲区的指针,该缓冲区包含实际数据。 std::string
具有构造函数,析构函数和赋值运算符,可自动管理包含实际字符数据的额外缓冲区。这包括重新分配,复制数据,更新内部指针以及在需要额外存储时释放先前的缓冲区。包含实际数据的缓冲区的大小不计入std::string
的大小,只有指向它的指针。 std::string
的每个实例,在其整个生命周期中,只直接包含恒定数量的成员,这些成员都具有恒定的大小。在c ++中,所有类型都具有编译时常量大小。
有关string
的简化实施,请参阅Rule of five,了解其工作原理。无论此指针指向的缓冲区内容如何,此示例中的类rule_of_five
的大小都只是char*
的大小。实际缓冲区在构造之后,期间或之后分配,这是在对象本身的初始分配已经完成之后。
编辑:在某些情况下,字符串可以在处理非常短的字符串时在内部存储它的字符数据。这是在其他容器中通常看不到的优化。请参阅this answer。