限制类中动态分配的数组或字符串的大小

C++ Limit the size of a dynamically allocated array or string inside a class?

本文关键字:字符串 数组 动态分配      更新时间:2023-10-16

假设我有一个类,它包含一个指向string对象的指针:

string *name;

在构造函数中,我将为它分配内存:

*name = new string[256];

这种方式的大小限制是由构造函数设置的,但是有没有一种方法来限制大小在类本身的指针声明?

上面的

是错误的!应该(可能)

*name = new char[256];

这样做通常不是一个好主意。如果您试图限制最终用户提供的大小,那么您应该在接收输入时应用限制检查。但是,在内部,您应该在程序中只使用std::string,而不强制其大小。例如:

 namespace {
 const int kMaxInputSize = 256;
 bool IsInputValid(const string& user_input) {
   return user_input.size() < kMaxInputSize;
 }
 // ...
 }
 // ...

现在,从技术上讲,您可以使用char name[256]来硬编码最多可容纳256个字符的字符串(包括空终止符),但这非常容易出错,并且不建议。

如果你的编译器支持c++ 2011标准的特性,那么你可以这样定义类

#include <iostream>
#include <string>
class A
{
private:    
    static const size_t N = 26;
    std::string *name = new std::string[N];
public:
    typedef size_t size_type;
    ~A() { delete [] name; }
    std::string & operator []( size_type i )
    {
        return name[i];
    }
    const std::string & operator []( size_type i ) const
    {
        return name[i];
    }
    size_type size() const { return N; }
    // Definitions of copy/move constructors and copy/move assignment operators
};
int main() 
{
    A a;
    for ( A::size_type i = 0; i < a.size(); i++ )
    {
        a[i] += char( 'A' + i % 26 );
    }
    for ( A::size_type i = 0; i < a.size(); i++ )
    {
        std::cout << a[i] << ' ';
    }
    std::cout << std::endl;
    return 0;
}

输出为

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

不要忘记定义析构函数、复制/移动构造函数和复制/移动赋值操作符。

也可以使用智能指针std::unique_ptr代替原始指针