我有以下类(class):
class A {
A(B* b, unsigned int size_in);
private:
unsigned int size;
// Pointer whose address and pointed-to data shouldn't be changed
const char* const p1;
// Pointer which should hold a copy of p1's data (at another location in the memory).
// Shouldn't ever be changed once copied from p1
const char* const p1_copy;
};
我想了解我应该如何构建构造函数,我想要一些这样的功能:
A::A(B* b, unsigned int size_in) :
size(size_in), p1(b->GetPtr() + b->GetOffset())
{
p1_copy = new char[size];
memcpy(p1_copy, p1, size);
}
但我显然不能对 p1_copy 这样做,因为它是 const 并且只能在初始化列表中初始化(而且 memcpy
不能与 const
一起使用指针作为第一个参数)。
仅供引用构造函数执行后,我将永远不会更改p1
或p1_copy
。
执行此操作的正确方法是什么?
谢谢!
最佳答案
一个选择是创建一个函数来复制字符串:
char* copyString(const char* s, size_t size) {
char* copy = new char[size];
memcpy(copy, s, size);
return copy;
}
A::A(B* b, unsigned int size_in) :
size(size_in), p1(b->GetPtr() + b->GetOffset()),
p1_copy(copyString(p1, size_in))
{
}
我更喜欢的另一个选择是使用 std::string
而不是原始指针:
class A {
//...
const std::string p1_copy;
};
A::A(B* b, unsigned int size_in) :
size(size_in), p1(b->GetPtr() + b->GetOffset()),
p1_copy(p1, p1 + size_in)
{
}
关于c++ - 如何将 const 指针初始化为未知大小的 const 数据(需要分配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30962500/