c++ - `string s("hello") ;` and ` string s = "hello";` 有区别吗

标签 c++ initialization variable-assignment copy-constructor assignment-operator

标题说明了一切。但是,请将 string 作为任何类的占位符。

std::string s1("hello");  // construct from arguments
std::string s2 = "hello"; // ???
std::string s3;           // construct with default values
s3 = "hello";             // assign

我想知道 s2 的语句是否与 s1s3 的语句相同。

最佳答案

案例s2copy initialization .它是初始化,而不是 s3 的赋值.

注意对于 std::string ,效果与s1相同和 s2 ,将调用适当的构造函数(即 std::string::string(const char*) )来构造对象。但是复制初始化和direct initialization是有区别的。 (s1 的情况);对于复制初始化,将不考虑显式构造函数。假设std::string::string(const char*)声明explicit ,这意味着从 const char* 的隐式转换至 std::string不允许;那么第二种情况将不会再次编译。

Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

关于c++ - `string s("hello") ;` and ` string s = "hello";` 有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41846295/

相关文章:

c++ - 什么是 msvc_make.bat?

c# - 从 C# 调用 QuantLib 方法的最佳方式是什么

c++ - 在 Qt Creator 中链接 EGL?

当被询问时,C 在运行时将数组初始化和重新初始化为零

haskell - 让 5 = 10 做什么?这不是赋值操作吗?

python - 为满足条件的第一行中的数据框赋值

c - 初始化char数组的不同方法,它们是否正确?

c++ - 通知线程是否总是需要在修改期间锁定共享数据?

c++ - 在 C 或 C++ 中是否使用未初始化的指针?

c - 是否可以在初始化程序中使用三元运算符初始化静态数组?