Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何初始化指向未知大小的常量数据的常量指针(需要alloc)_C++_Pointers_Constructor_Constants - Fatal编程技术网

C++ 如何初始化指向未知大小的常量数据的常量指针(需要alloc)

C++ 如何初始化指向未知大小的常量数据的常量指针(需要alloc),c++,pointers,constructor,constants,C++,Pointers,Constructor,Constants,我有以下课程: 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 l

我有以下课程:

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执行此操作,因为它是常量,只能在初始化列表中初始化(而且
memcpy
不能将
const
指针用作第一个参数)

FYI:执行构造函数后,我将永远不会更改
p1
p1\u copy

正确的方法是什么


谢谢大家!

对此可能有几种不同的解决方案,但这是
const_cast
设计的典型情况-您暂时希望覆盖某个对象的
const
属性

因此,您需要这样的操作(可以不使用临时变量,但需要更多的const_cast操作,而且不太清楚)

  char* tmp = new char[size];
  memcpy(tmp, p1, size);
  const_cast<const char*>(p1_copy) = tmp;
char*tmp=newchar[size];
memcpy(tmp、p1、尺寸);
const_cast(p1_copy)=tmp;

一个选项是创建一个函数来复制字符串:

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)
{
}

不确定这是否是正确的/最好的方法,但你不能像这样做吗

const char* copy(const char* a, int size) {
    const char* ret = new char[size];
    memcpy(ret, a, size);
    return ret;
}
然后

A::A(B* b, unsigned int size_in) :
  size(size_in), p1(b->GetPtr() + b->GetOffset()), p1_copy(copy(p1, size)) {}