C ++ passes string literal instead of const std :: string &?

I have the following code that compiles without warning (-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 a new line is output. What's happening?

If I did this inside things:

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

then it works great!

+7
source share
3 answers

The reason this happens is because it essentially compiles under the hood.

Foo o(std::string("wurd"));

Foo , . , . , , , Foo.

, memebr const std::string& const std::string.

+20

, 'str' , arg, 's'. - arg, 's'. ( ftn), .

, str , , .

const std::string str;

arg, , Foo.

+2

Continuing the answers that were given earlier: If you want to avoid copying data, you can change the member parameter and the Foo constructor to const char*.

class Foo
{
public:
    Foo(const char* s) : str(s)
    { }

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

private:
    const char* str;
};


class Bar
{
public:

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


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

    return 0;
}
0
source

All Articles