Sign in to follow this  

std::string question

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
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.

std::string GetFileName()
char szBuff[MAX_PATH];
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this