调用ImGui::InputText()
需要一个char
数组,我需要从 a 初始化该数组,std::string
然后将内容传输回std::string
. 以最简单的形式:
char buf[255]{};
std::string s{"foo"};
void fn() {
strncpy( buf, s.c_str(), sizeof(buf)-1 );
ImGui::InputText( "Text", buf, sizeof(buf) );
s=buf;
}
buf
但是,让两个缓冲区(以及在其中分配的缓冲区std::string
)都做同样的事情似乎很浪费。我可以buf
通过仅使用std::string
和一个简单的包装器“X”来避免缓冲区和复制到缓冲区和从缓冲区复制。我不关心效率,我只想要调用站点上最简单的代码。这段代码确实有效,但它安全吗?有更好的方法吗?
class X {
public:
X(std::string& s) : s_{s} { s.resize(len_); }
~X() { s_.resize(strlen(s_.c_str())); }
operator char*(){ return s_.data(); }
static constexpr auto len() { return len_-1; }
private:
std::string& s_;
static constexpr auto len_=255;
};
std::string s{"foo"};
void fn() {
ImGui::InputText( "Text", X(s), X::len() );
}