Hi, I have a question.

Using the following code:

#include <iostream>
int main()
{
	std::string s1;
	std::cout << s1.capacity() << std::endl;

	system ("PAUSE");
	return 0;
}

In Ubuntu/KDevelop the output is 0.

In Windows/V.Studio the output is 15.

Can anyone suggest why it happens?

I'm somewhat stumped by it's occurrence.

Thanks very much, much appreciated.

The string member capacity() is defined as:

Return size of allocated storage
Returns the size of the allocated storage space in the string object.

Notice that the capacity is not necessarily equal to the number of characters that conform the content of the string (this can be obtained with members size or length), but the capacity of the allocated space, which is either equal or greater than this content size.

Notice also that this capacity does not suppose a limit to the length of the string. If more space is required to accomodate content in the string object, the capacity is automatically expanded, or can even be explicitly modified by calling member reserve.

The real limit on the size a string object can reach is returned by member max_size.

It is possible to speculate that different operating systems employ different memory management strategies. It is also possible to speculate that the same operating system will handle memory allocation differently among different machines. To go one step further, perhaps the same operating system will allocate memory differently at times on the same machine (depending on what processes are running, available memory etc.)

A lot of variables at play here to come up with a rock-solid answer. Since OS design is usually company-top-secret, perhaps we'll never know exactly how one OS handles memory allocation in comparison to others.

The capacity of a container class has nothing to do with the OS, it's an internal mechanism of the C++ implementation. In other words, capacity will potentially return a different value for every single implementation of the standard library you use because the author of each library chooses how to manage memory growth for the container.

Now the max_size member function for containers is more likely to depend on the OS.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.