std::string 赋值运算符如何工作
How does std::string assign operator work?
我试图弄清楚以下语句在C++中是如何工作的:
std::string a = "simple_text";
是首先用空文本初始化"a"对象,然后将"simple_text"分配给它,还是"a"对象立即用"simple_text"初始化?
我将不胜感激。
如果构造函数没有用关键字 explicit
定义,那么编译器可以适应
std::string a = "simple_text";
自
std::string a = std::string("simple_text");
在这种情况下,它不是=
运算符,而是CCTOR
运算符。由于a
尚未构建,因此必须构建它。
您可以在以下示例中体验到这一点:
class Foo{
int bar;
public:
Foo(int anInt): bar(anInt){
std::cout << "CTOR calledn";
}
Foo(Foo& aFoo){
this->bar = aFoo.bar;
std::cout << "CCTOR calledn";
}
Foo& operator=(Foo& aFoo){
this->bar = aFoo.bar;
std::cout << "operator = calledn";
return *this;
}
};
int main(){
Foo aFoo(5);
Foo bFoo = aFoo; // since bFoo is not instantiated yet, the CCTOR constructs it.
return 0;
}
输出将是
CTOR called
CCTOR called
此语句
std::string a = "simple_text";
不是复制赋值运算符。它是对象的定义,因此使用了构造函数。
此语句等效于
std::string a = std::string( "simple_text" );
首先创建一个临时对象 std::string( "simple_text" ); 使用带有参数const char *
的构造函数,然后使用 move 构造函数将此对象移动到 a 中。
但是,C++标准允许消除移动构造函数的调用。所以定义
std::string a = "simple_text";
将简单地等同于
std::string a( "simple_text" );
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- <string> 结构中的矢量无法正常工作
- string.find() 无法正常工作
- std::string::擦除没有按我预期工作
- 'const std::string&s = nullptr' 如何作为可选参数工作
- `std :: string :: find_last_of()如何实际工作
- std::string 上的 substr 无法正常工作,因为存在一些不可见但看起来像空格的字符
- "string::erase"如何在 cpp 中工作?
- std::string 赋值运算符如何工作
- 我在不使用string.h的情况下写了一个C++回文.在没有 Do-While 循环的情况下,它可以正常工作.但是当我尝
- std::string::find在c++中未按预期工作
- c ++比较std::string将无法工作,如果我不使用Code::Blocks但cygwin编译
- 采用“std::string”的显式构造函数得到“char*”,工作正常
- getline(cin,string)与cin.ignore()一起不工作
- basename-freebsd使用std::string可以正常工作,但不使用
- c++转换为String最终停止工作
- std::atomic<std::string> 是否正常工作?
- 我的指向 std::string 对象的指针列表无法正常工作,我无法弄清楚为什么
- Std::string不能与Std::set一起工作