我的问题关于复制构造和重新分配的机制。
我有一个类,用于收集字符串。在向收集中添加字符串后,将复制并存储到向量中。但我也需要访问所有字符串的集合作为 const char * const*
,因此我还通过.c_str()
存储每个字符串数据的指针。
class MyStrings {
private:
std::vector<std::string> names;
std::vector<const char*> cStringPointers;
public:
const char *const *Data() const
{
return this->cStringPointers.data();
}
void Add(const std::string &name)
{
// copy [name] and store the copy in [this->names].
this->names.push_back(name);
// Store the pointer to the data of the copy.
this->cStringPointers.push_back(this->names.back().c_str());
}
}
我知道,将指针存储在向量元素中是不好的,因为当向量重新分配内存时,这些指针将不再有效。
但是我仅存储数据的指针。所以这是我的想法:
如果“names”被调整大小,它将移动构造其中包含的所有字符串,因此这些字符串将不会分配新的内存,而是只使用已经分配的内存,因此我的 cStringPointers 中的指针仍然有效。
我的问题现在很简单:是否有什么我错过的东西,使得这段代码不安全或导致未定义的行为?
(假设我不使用任何异乎寻常的架构或编译器。)
c_str
。 - 463035818_is_not_a_number