显式复制构造函数 [英] Explicit copy constructor
问题描述
我已经扩展了std :: string,以满足我将自定义函数编译到 CustomString 字符串类中的需要
I have extended std::string to fulfil my needs of having to write custom function build into string class called CustomString
定义的构造函数:
I have defined constructors:
class CustomString : public std::string {
public:
explicit CustomString(void);
explicit CustomString(const std::string& str);
explicit CustomString(const CustomString& customString);
//assignment operator
CustomString& operator=(const CustomString& customString);
... };
在第三个构造函数(复制构造函数)和赋值运算符中,它的定义是:
In the third constructor (copy constructor) and assignment operator, whose definition is:
CustomString::CustomString(const CustomString& customString):
std::string(static_cast<std::string>(customString))
{}
CustomString& CustomString::operator=(const CustomString& customString){
this->assign(static_cast<std::string>(customString));
return *this;
}
首先,因为这是一个显式这意味着需要显式转换来分配给另一个CustomString对象;它抱怨作业。
First since this is an "explicit"; meaning an explicit cast is needed to assign to another CustomString object; it's complaining about the assignment.
CustomString s = CustomString("test");
我不知道明确地在哪里投放。
I am not sure where exactly is casting needed explicitly.
如果复制构造函数不是显式的,但我想知道并实现显式定义而不是猜测正确的转换代码工作正常。
The code works alright if copy constructor is not explicit but I would like to know and implement explicit definition instead of "guessing proper cast".
推荐答案
显式拷贝构造函数意味着拷贝构造函数不会被隐式调用,这是在表达式中发生的: p>
The explicit copy constructor means that the copy constructor will not be called implicitly, which is what happens in the expression:
CustomString s = CustomString("test");
此表达式字面意思是:创建一个临时 CustomString
使用接受 const char *
的构造函数。隐式调用 CustomString
的复制构造函数将该临时变量复制到 s
中。
This expression literally means: create a temporary CustomString
using the constructor that takes a const char*
. Implicitly call the copy constructor of CustomString
to copy from that temporary into s
.
现在,如果代码是正确的(即如果复制构造函数不是显式的),编译器将避免创建临时并通过构造 s
直接与字符串文字。
Now, if the code was correct (i.e. if the copy constructor was not explicit), the compiler would avoid the creation of the temporary and elide the copy by constructing s
directly with the string literal. But the compiler must still check that the construction can be done and fails there.
您可以显式调用复制构造函数:
You can call the copy constructor explicitly:
CustomString s( CustomString("test") );
但是我建议你避免临时的,只是创建 s
与 const char *
:
But I would recommend that you avoid the temporary altogether and just create s
with the const char*
:
CustomString s( "test" );
这是编译器会做什么...
Which is what the compiler would do anyway...
这篇关于显式复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!