c++ - C++中的临时问题

标签 c++ boost

我有一段使用 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/

相关文章:

c++ - 使用 boost::function::target 获取函数指针时的空指针

c++ - 延迟窗口在mfc上显示文本

c++ - C++发送邮件的代码

c++ - boost asio iostream - 如何获取本地IP地址

boost 消息队列

python - Boost Python Numpy - 未定义的初始化引用

C++ move 语义 : why copy assignment operator=(&) is called instead of move assignment operator=(&&)?

c++ - std::async,std::promise 和 std::packaged_task 会阻塞主线程,它们是什么意思?

c++ - Qt/C++ : Getting the data at a certain cell in a QTableView

c++ - R6010-当 boost 文件系统的重命名或 copy_file 方法被命中时,中止被命中