我有一段使用 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();
}
如果我直接将我的第二个参数作为 const char* 发送,我知道它会创建一个临时对象,而我的构造函数参数将只在构造函数中可见,然后它会丢失,因为引用了临时对象。
我的问题是,为什么第一个参数(字符串)没有发生同样的事情,因为我也直接将他作为 const char* 发送,但值没有在构造函数之外丢失?
最佳答案
Shell shell("ls", Path); // BAD - just happens to work as you expected.
未定义的行为 - 任何事情都可能发生,包括按照您的预期行事。在您的情况下,临时分配的内存恰好没有被覆盖。
关于c++ - C++中的临时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5634565/