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?
Asked
Active
Viewed 2,481 times
2

visionedison
- 151
- 1
- 9
-
try it out here and compare the generated assembly http://gcc.godbolt.org/ – Bryan Chen Oct 17 '14 at 02:21
-
Both use constructors. There is no assignment, nor `operator=` used in your shown code. – chris Oct 17 '14 at 02:40
-
possible duplicate of [Is there a difference in C++ between copy initialization and direct initialization?](http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati) – Galik Oct 17 '14 at 03:12
3 Answers
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.

Brian Bi
- 111,498
- 10
- 176
- 312
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.

Clinton
- 22,361
- 15
- 67
- 163
-
1It would never call assignment operator here because both x1 and x2 are initialized, they are not assigned. – kraskevich Oct 17 '14 at 03:33
-
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.

Bill Lynch
- 80,138
- 16
- 128
- 173