我有这段代码使用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();
}
Run Code Online (Sandbox Code Playgroud)
如果我发送我的第二个参数direclty作为一个const char*我知道它将创建一个临时的,我的构造函数参数只会在构造函数中可见,然后它丢失,因为引用临时.
我的问题是,为什么第一个参数,即字符串发生同样的事情,因为我也将它作为const char*直接发送给他,但是值在构造函数之外不会丢失?
Shell shell("ls", Path); // BAD - just happens to work as you expected.
Run Code Online (Sandbox Code Playgroud)
未定义的行为 - 任何事情都可能发生,包括按照您的期望行事.临时分配的内存恰好在你的情况下没有被覆盖.
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |