I ran into one problem, and I can not understand why this is happening.

Suppose there is some function

vector<std::string> split(const std::string &s, char delim) {} 

If you call it simply as vector<string>s = split("pam.pam", '.'); then everything will be fine and the code will work. However, if you remove the keyword const in the arguments, the program will not compile. Why is that?

    1 answer 1

    In response to your "pam.pam" compiler creates a temporary object of type std::string . Lvalue links can be bound to temporary objects only if these links are const . It always has been.

     const std::string &s1 = "pam.pam"; // <- Все в порядке std::string &s2 = "pam.pam"; // <- А так нельзя 

    The question here is, why did you suddenly need to remove this const . If you want to modify s inside your function and at the same time consider that it “goes without saying” that the value of the argument passed by the user will be modified / damaged / destroyed, you can provide overloads

     vector<std::string> split(std::string &s, char delim) { ... } vector<std::string> split(std::string &&s, char delim) { return split(s, delim); } 

    If you want the argument value not to be destroyed and at the same time there is no copying cost when it is not needed, then the easiest way to do it

     vector<std::string> split(std::string s, char delim) { ... } 

    Both options allow you to do

     split("pam.pam", '.'); 
    • why in the code vector<std::string> split(std::string s, char delim) you speak about the absence of copying costs, if both arguments are passed by value? - Bogdan
    • @Bogdan: I'm talking about the absence of extra costs for copying. If the user wants to keep the argument intact, then no way to do without copying and copying will be. If the user doesn’t care, he can pass the argument through std::move and instead of copying it will be moved. The same thing will happen by itself with temporary objects. That is, there will be no copying - it will be moving. - AnT