string str1("someString");
string str2 = string(str1);//how many copies are made here
//copy2 = copy1?
When you assign a string with string(otherString), does it copy the value in the parentheses then copy that value to the variable?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In real life there will be one copy, though theoretically it depends on the version of the language your compiler implements.
string(str1)is going to create a temporary that’s a copy ofstr1.In C++98/03, the compiler will theoretically use copy initialization to initialize
str2from that temporary, so in theory a second copy will be made at that point. In reality, you’ll probably have a hard time finding a compiler that doesn’t elide one of those copy operations though (at least if optimization is enabled).In C++11,
std::stringhas a move constructor (one that takes an rvalue reference), which should be used to initializestr2, so the second copy shouldn’t even theoretically happen.