Jump to content
  • Advertisement
Sign in to follow this  
godsenddeath

std::string question

This topic is 3738 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

ok, c++ strings dynamically allocate memory as needed right? when using one as a buffer such as: //in Win32 context std::string Buffer; OPENFILENAME ofn; ofn.lpstrFile = &Buffer; //end does it still dynamiclly size to hold whatever is needed? thanks

Share this post


Link to post
Share on other sites
Advertisement
You'll need to look into basic_string::c_str().

What you're doing right now will blow up horribly.

Share this post


Link to post
Share on other sites
No, the address of the string object is not a pointer to the string buffer (C-style string). String only provides constant access to it's internal buffer through it's c_str() method.

However, as lpstrFile is meant to be written to, you probably can't use a std::string for that at all (std::string is only modifiable through it's member functions and you can be quite sure that GetOpenFileName is not going to use std::string methods, being a C API). If this dialog is for selecting only one file you might just use a fixed-size char array on the stack (the file-name probably can't/shouldn't be longer than MAX_PATH characters).

If you feel you need to allocate the buffer dynamically you might use std::vector<char>. You get the address to the writable buffer through &vec[0], and it would be fine as long as the vector's size is what you report in the OPENFILENAME's nMaxFile member.

Share this post


Link to post
Share on other sites
No, for two reasons.

Firstly, the address of a std::string is not the same as a char*. If you want to get the string data as a const char*, you can use the c_str() member function.
Secondly, as soon as you convert a std::string into a different type (char* or const char*), it's no longer a std::string, and won't reallocate memory or anything.

To do what you want to do, you should pass in a normal char array, and then convert it to a std::string (implicity) when you return it.
E.g.:

std::string GetFileName()
{
char szBuff[MAX_PATH];
OPENFILENAME ofn;
ofn.lpstrFile = szBuff;

// Call GetOpenFileName, etc

return szBuff; // implicitly converts to std::string because function return type is std::string
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!