0

I have this code in C++

class ConstantTest
{
public:
    typedef set<string> StrSet;

    ConstantTest (const uint16_t & id = 0, const string & str = "Empty", 
                  StrSet & set = StrSet()) : 
                  // Works with: const StrSet & set = StrSet()
                  m_id (id), m_str (str), m_set (set) 
    { }
private:
    uint16_t m_id;
    string   m_str;
    StrSet   m_set;
};

I want to know why it doesn't work without the const keyword in the StrSet parameter. With the keyword works just fine, but without it I get this message:

test_const.cpp:17:41: error: could not convert ‘std::set<std::basic_string<char> >()’ from ‘ConstantTest::StrSet {aka std::set<std::basic_string<char> >}’ to ‘ConstantTest::StrSet& {aka std::set<std::basic_string<char> >&}’
                   StrSet & set = StrSet()) :
                                         ^
LuissRicardo
  • 167
  • 1
  • 11
  • 3
    You cannot set a non `const` reference to a temporary rvalue, as you're doing with your default parameter assignment. Also I don't see any need for a non `const` reference in your case. – πάντα ῥεῖ Nov 10 '14 at 15:57
  • BTW, using the same name for a (template) type and a variable isn't the best idea. – Mat Nov 10 '14 at 16:05
  • @πάνταῥεῖ Thank you. I made this code just for posting it here, I got the issue on a bigger project. I need the `const` because I'm passing as parameter big collections of data, so it's cheaper thant passing them as value. @Mat Yes, sorry. I didn't notice. I made this code fast. It does work though. – LuissRicardo Nov 10 '14 at 16:17

0 Answers0