简体   繁体   English

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

[英]How to initialize a const pointer to a const data of unknown size (need alloc)

I have the following 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;
};

I'm trying to understand how I should build the constructor, I want something of this functionality: 我试图了解如何构建构造函数,我想要一些此功能:

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

But I obviously can't do that to p1_copy because it is const and can only be initialized in an initialization list (also memcpy wouldn't work with a const pointer as the 1st argument). 但是我显然不能对p1_copy做到这一点,因为它是const且只能在初始化列表中进行初始化(而且memcpy不能将const指针用作第一个参数)。

FYI: after the constructor is executed, I will never change p1 or p1_copy . 仅供参考:执行构造函数后,我将永远不会更改p1p1_copy

What's the proper way to do this? 正确的方法是什么?

Thank you! 谢谢!

There are probably a few different solutions for this, but this is the typical case that const_cast was designed for - where you temporarily want to override the const ness of something. 可能有几种不同的解决方案,但这是const_cast设计的典型情况-在这里您临时要重写某些内容的const

So, you want something like (it can be done without a temporary variable, but you need more const_cast operations, and it's much less clear. 因此,您需要类似的东西(它可以在没有临时变量的情况下完成,但是您需要更多的const_cast操作,而且不清楚。

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

One option could be to create a function which makes a copy of the string: 一种选择是创建一个复制字符串的函数:

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

Another option, which I would prefer, is just to use std::string instead of raw pointer: 我更喜欢的另一种选择是仅使用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)
{
}

Not sure if this is the proper/best way, but couldn't you do something like 不知道这是否是正确的/最好的方法,但是你不能做这样的事情

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

and then 接着

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM