std::string 赋值运算符如何工作

How does std::string assign operator work?

本文关键字:工作 string 赋值运算符 std 何工作      更新时间:2023-10-16

我试图弄清楚以下语句在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" );