[英]What happens when you initialize a const reference by conversion constructor?
What happens when you initialize a const reference by conversion constructor? 通过转换构造函数初始化const引用时会发生什么? Is it any different from an ordinary assignment?
与普通作业有什么不同吗? Look at this code:
看这段代码:
void func(const char* cstr) {
std::string S1 = cstr;
const std::string& S2 = cstr;
}
Is there any practical difference between S1 and S2? S1和S2之间有什么实际区别吗? Why would you want to use the second expression?
为什么要使用第二个表达式?
Is there any practical difference between S1 and S2?
S1和S2之间有什么实际区别吗?
In terms of performance, the answer is no. 在性能方面,答案是否定的。 Both instructions invoke converting constructor and allocate memory, then copy the the
char
array in the internal dynamic memory of std::string
instance. 两条指令均调用转换构造函数并分配内存,然后将
char
数组复制到std::string
实例的内部动态内存中。
In term of syntax, the answer is obviously the const
-ness: in the successive block of the function the object handled by S2
cannot be modified. 在语法上,答案显然是
const
:在函数的后续块中,无法修改S2
处理的对象。
With std::string S1 = cstr;
使用
std::string S1 = cstr;
S1
is move-constructed from a temporary. S1
是从临时移动构造的。 That move-construct should probably be elided, but should be accessible. 该移动构造可能应该被省略,但是应该可以访问。 As not
const
, S1
can be modified. 由于不是
const
,可以修改S1
。
With const std::string& S2 = cstr;
使用
const std::string& S2 = cstr;
S2
is a const reference to a temporary string, with extended lifetime. S2
是对临时字符串的const引用,具有延长的生存期。 As const
, S2
cannot be modified. 作为
const
,不能修改S2
。
For type without move/copy constructor as 对于没有移动/复制构造函数的类型
struct S {
S() = default;
S(const S&) = delete;
S& operator =(const S&) = delete;
};
You may use the second form, but not the first one: 您可以使用第二种形式,但不能使用第一种形式:
S s1 = S{}; // Invalid
const S& s2 = S{}; // Valid
S&& s3 = S{}; // Valid too.
You get a const
reference to the S1 string, and the compiler enforces the const
of the value. 您将获得对S1字符串的
const
引用,并且编译器将强制执行该值的const
。 If you try to modify S2
it will not compile. 如果尝试修改
S2
,它将无法编译。 For local variables it doesn't make much sense, except when you don't trust yourself to not modify S2
, or when you are doing code refactorings moving things around and you want to be sure that S2
is never changed. 对于局部变量,这没有多大意义,除非您不信任自己不要修改
S2
,或者在进行代码重构时要移动一些东西,并且您要确保S2
从未更改。
But if you pass a string as an argument to a function you can use a const
reference to avoid a costly copy: 但是,如果将字符串作为参数传递给函数,则可以使用
const
引用来避免昂贵的复制:
void f(const std::string& S2) { ... }
const
in general won't help the compiler to perform optimizations to the code since you can always use const_cast
to remove the const
of a variable. 通常,
const
不会帮助编译器对代码进行优化,因为您始终可以使用const_cast
删除变量的const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.