I am learning C++ from the beginning and I don’t get the whole strings topic.
What is the difference between the following three codes?
std::string s = std::string("foo");std::string s = new std::string("foo");std::string s = "foo";
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.
This creates a temporary
std::stringobject containing “foo”, then assigns it tos. (Note that compilers may elide the temporary. The temporary elison in this case is explicitly allowed by the C++ standard.)This is a compiler error. The expression
new std::string("foo")creates anstd::stringon the free store and returns a pointer to anstd::string. It then attempts to assign the returned pointer of typestd::string*tosof typestd::string. The design of thestd::stringclass prevents that from happening, so the compile fails.C++ is not Java. This is not how objects are typically created, because if you forget to
deletethe returnedstd::stringobject you will leak memory. One of the main benefits of usingstd::stringis that it manages the underlying string buffer for you automatically, sonew-ing it kind of defeats that purpose.This is essentially the same as #1. It technically initializes a new temporary string which will contain “foo”, then assigns it to
s. Again, compilers will typically elide the temporary (and in fact pretty much all non-stupid compilers nowadays do in fact eliminate the temporary), so in practice it simply constructs a new object calledsin place.Specifically it invokes a converting constructor in
std::stringthat accepts aconst char*argument. In the above code, the converting constructor is required to be non-explicit, otherwise it’s a compiler error. The converting constructor is in fact non-explicitforstd::strings, so the above does compile.This is how
std::strings are typically initialized. Whensgoes out of scope, thesobject will be destroyed along with the underlying string buffer. Note that the following has the same effect (and is another typical waystd::strings are initialized), in the sense that it also produces an object calledscontaining “foo”.However, there’s a subtle difference between
std::string s = "foo";andstd::string s("foo");, one of them being that the converting constructor can be eitherexplicitor non-explicitin the above case.