I have this piece of code that prints the content of a directory using Boost.Filesystem:
class Shell {
private:
const string& command;
const path& firstPath;
const path& secondPath;
public:
// constructor
Shell(const string& _command, const path& _firstPath, const path& _secondPath = path()): command(_command), firstPath(_firstPath), secondPath(_secondPath) {}
//destructor
~Shell() {}
//execute commands
void executeCommand()
{
if(command.compare("ls"))
{
ls();
}
}
void ls()
{
if(exists(firstPath))
{
vector<path> vecPath;
copy(directory_iterator(firstPath), directory_iterator(), back_inserter(vecPath));
sort(vecPath.begin(), vecPath.end());
for(vector<path>::iterator it = vecPath.begin(); it != vecPath.end(); ++it)
{
cout << *it << endl;
}
}
}
};
int main(int argc, char** argv)
{
path Path = "c:\\workspace";
Shell shell("ls", Path); // GOOD
// Shell shell("ls", "c:\\workspace"); BAD creates temporary !!
shell.executeCommand();
}
If I send my second argument direclty as a const char* I know that it will create a temporary and my constructor argument will only be visible in the constructor, then its lost, because of the reference to temporary.
My question is, why isnt the same thing happening to the first argument, the string, because I am sending him also as a const char* directly, but the value isnt lost outside of the constructor ?
Undefined Behavior – Anything can happen, including acting like you expect. The memory allocated by the temporary just happened to not be overwritten in your case.