gpt4 book ai didi

c++ - 字符串是否在其构造函数中复制数据

转载 作者:行者123 更新时间:2023-12-03 11:05:46 26 4
gpt4 key购买 nike

在以下函数中(从另一个 Stackoverflow 帖子修改),我尝试使用 unique_ptr所以new分配的内存稍后被释放。

这样做是否安全std::wstring(res.get())这里?即,将 res在调用字符串构造函数时被复制,以便如果 new 分配的内存被释放,返回的值不会变成垃圾?

std::wstring narrow_to_wide_str(const std::string& input) {
size_t size = input.size() + 1;
size_t out_size;
std::unique_ptr<wchar_t[]> res{ new wchar_t[size] };
mbstowcs_s(&out_size, res.get(), size, input.c_str(), size - 1);
return std::wstring(res.get());
}

最佳答案

Is it safe to do std::wstring(res.get()) here?



是的。

来自 std::basic_string::basic_string :

basic_string( const CharT* s, const Allocator& alloc = Allocator() ); (5)

5) Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer). This constructor is not used for class template argument deduction if the Allocator type that would be deduced does not qualify as an allocator. (since C++17)



(强调我的。)

关于c++ - 字符串是否在其构造函数中复制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58688487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com