-2

I am having a constructor like this:

class class_foo{
    std::string s_;
    class_foo(std::string& s) : s_(s){};
}

I know I can do:

std::string s = "test";
cf = class_foo(s);

Is there a way to do:

cf = class_foo("test");

But is says: note: candidate constructor not viable: expects an l-value for 3rd argument

@eerorika was right. I can simply use a const like here: link

Julian
  • 909
  • 8
  • 21

1 Answers1

1

I am having a constructor like this:

void class_foo(std::string& s) : s_(s){};

A constructor cannot have a return type (even void).

Is there a way to do:

cf = class_foo("test");

Not if you want to keep the argument as non-const reference. It is however unclear why you want it to be non-const reference. Perhaps it doesn't need to be a non-const reference? If you don't intend to modify the argument, then you should use a reference to const. Then your suggested construction would work.

eerorika
  • 232,697
  • 12
  • 197
  • 326