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

前端 未结 3 741
旧时难觅i
旧时难觅i 2021-02-14 10:01

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

#include 
#include 

using namespace std;

cla         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-14 10:41

    Extending on the answers given before: If you want to avoid the copy of the data, you can change the member and constructor parameter of Foo 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;
    }
    

提交回复
热议问题