限制类中动态分配的数组或字符串的大小
C++ Limit the size of a dynamically allocated array or string inside a class?
假设我有一个类,它包含一个指向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
代替原始指针
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组