c++ - 如何将 const 指针初始化为未知大小的 const 数据(需要分配)

标签 c++ pointers constructor constants

我有以下类(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 一起使用指针作为第一个参数)。

仅供引用构造函数执行后,我将永远不会更改p1p1_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/

相关文章:

c++ - C++程序中随机调用函数

c++ - 如何有效地将一系列 NumericVectors 组合成一个大的 NumericVector?

c - 我无法确定为什么这个 C 程序会给我这个答案

c++ - 按地址从 vector 中删除一个元素

java - java中的参数化构造函数是否必须有主体?

c++ - 如何为 ON_COMMAND 处理程序声明 ID?

c++ - C++的类图

Objective-c 符号 ** & +-

Javascript 'this' 嵌套函数内的关键字

python - 使用类构造函数作为函数创建线程