我正在编写一个String类MyString
(是的,作为作业),并且必须提供一个返回unique_ptr<char[]>
(而不是Vector
)的toCString
方法。不幸的是,我在将指针返回给调用者时失败了:结果总是填充了错误的内容——似乎我在堆栈上创建了指针和/或字符数组。
unique_ptr<char[]> MyString::toCString() const {
char *characters = new char[m_len];
char *thisString = m_string.get();
for (int i = 0; i < m_len; i++) {
characters[i] = *(thisString + m_start + i);
}
const unique_ptr<char[], default_delete<char[]>> &cString = unique_ptr<new char[m_len]>(characters);
return cString;
}
调试时,我总是得到预期的行为。问题仅发生在呼叫者网站上。我的错误在哪里?
我看到已经有了一个公认的答案,但这并不能解决问题。客户端出现问题是因为终止c字符串时不是null。
我不知道m_string是什么类型,所以让我们暂时假设它是std::string。你可以自己翻译实际的方法:
std::unique_ptr<char[]> MyString::toCString() const
{
// get length (in chars) of string
auto nof_chars = m_string.size();
// allocate that many chars +1 for the null terminator.
auto cString = std::unique_ptr<char[]>{new char[nof_chars + 1]};
// efficiently copy the data - compiler will replace memcpy
// with an ultra-fast sequence of instructions in release build
memcpy(cString.get(), m_string.data(), nof_chars * sizeof(char));
// don't forget to null terminate!!
cString[nof_chars] = ' ';
// now allow RVO to return our unique_ptr
return cString;
}
根据Christophe的建议,这里又是一个方法,用std::copy_n写成。请注意,std::copy[_xxx]函数套件都返回一个迭代器,该迭代器寻址最后一次写入之后的一个。我们可以使用它来节省重新计算null终止符的位置。标准图书馆不是很棒吗?
std::unique_ptr<char[]> MyString::toCString() const
{
// get length (in chars) of string
auto nof_chars = m_string.size();
// allocate that many chars +1 for the null terminator.
auto cString = std::unique_ptr<char[]>{new char[nof_chars + 1]};
// efficiently copy the data - and don't forget to null terminate
*std::copy_n(m_string.data(), nof_chars, cString.get()) = ' ';
// now allow RVO to return our unique_ptr
return cString;
}
不要像以前那样创建对unique_ptr的引用。相反,直接返回unique_ptr:move构造函数将处理所有内容:
return unique_ptr<char[], default_delete<char[]>>(characters);
由于您已经编辑了问题,现在您正在使用
unique_ptr<char[]> cString = unique_ptr<char[]>{new char[m_len]};
第一个改进:使用自动
auto cString = unique_ptr<char[]>{new char[m_len]};
第二个改进:你的标签是C+11,但如果你碰巧使用C+14,那么使用std::make_unique
,如下所示:
auto cString = std::make_unique<char[]>(m_len);
此外,正如Scott Meyers所说,如果您使用的是C+11,那么只需自己编写make_unique
函数即可。这并不难,而且非常有用。
http://ideone.com/IIWyT0
template<class T, class... Types>
inline auto make_unique(Types&&... Args) -> typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
{
return (std::unique_ptr<T>(new T(std::forward<Types>(Args)...)));
}
template<class T>
inline auto make_unique(size_t Size) -> typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0, std::unique_ptr<T>>::type
{
return (std::unique_ptr<T>(new typename std::remove_extent<T>::type[Size]()));
}