2

What is most appropriate in const std::string assignment/declaration? Using the constructor(e.g., const std::string WORD("hello");) or using equal operator(e.g., const std::string WORD= "hello";)? Does these things has difference in memory usage or time processes?

3

3 Answers 3

2

For any reasonable compiler, the code generated will be the same in both cases. Whether you should use direct initialization or copy-initialization in this case is essentially opinion-based.

Sign up to request clarification or add additional context in comments.

Comments

0

In both cases, generally compilers will remove the copies using "Return Value Optimisation" anyway. See this code on ideone here calls neither the ordinary constructor nor the assignment operator as it doesn't print that they're being called to screen:

That is:

#include <iostream>

class C
{
    public:
    C() {}
    C(const char[]) { std::cout << "Ordinary Constructor" << std::endl; }
    C& operator=(const char[]) { std::cout << "Assignment Operator" << std::endl; return *this; }
};

int main() {
    std::cout << "Start" << std::endl;
    C x1 = "Hello";
    C x2("Hello");
    std::cout << "End" << std::endl;
}

Simply outputs:

Start
End

It doesn't output:

Start
Assignment Operator
Ordinary Constructor
End

As C++ allows the copies to be skipped and the temporary to be constructed in place.

2 Comments

It would never call assignment operator here because both x1 and x2 are initialized, they are not assigned.
C x1 = "Hello"; means copy constructor, not assignment operator
0

The lines:

std::string x = "hello";
std::string x("hello");

both will only call the constructor of std::string. That is, they are identical, and neither will use the operator= overloads.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.