Printf和C++字符串

Bob*_*ano 2 c++ string printf c-str

所以我有以下代码:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    vector<string> strs;
    strs.push_back("happy");    
    const string& a1 = strs[0];
    strs.push_back("birthday");
    const string& a2 = strs[1];
    strs.push_back("dude");
    const string& a3 = strs[2];

    printf("%s\n", a1.c_str());     
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这很简单,但不起作用.该printf的不打印任何东西.如果我将其更改为:

const string& a1 = strs[0].c_str();
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下它的行为.

Bau*_*gen 8

您的push_back潜在调用(在您的情况下显然实际上)会使所有引用无效vector,即如果vector它太小而无法存储新元素.因此,除非确保容量足够大,否则不能vector在a之前使用任何引用.push_backvector

如果创建引用之前确保vector所有元素具有足够的容量(即通过使用std::vector::reserve),则第一个版本将按预期工作.

您的第二个示例有效,因为您创建了一个新的临时string(其生命周期延长到引用的生命周期)引用绑定到.