c++ passing a string literal instead of a const std::string&?

I have the following code which compiles with no warnings (-Wall -pedantic) with g++

#include <iostream>
#include <string>

using namespace std;

class Foo
{
public:
    Foo(const std::string& s) : str(s)
    { }

    void print()
    {
        cout << str << endl;
    }

private:
    const std::string& str;
};


class Bar
{
public:

    void stuff()
    {
        Foo o("werd");
        o.print();
    }
};


int main(int argc, char **argv)
{
    Bar b;
    b.stuff();

    return 0;
}

But when I run it, only the newline is printed out. What is going on?

If I were to do this inside stuff:

string temp("snoop");
Foo f(temp);
f.print();

then it works fine!

7
задан Victor Parmar 6 December 2010 в 18:44
поделиться