gpt4 book ai didi

C++只调用一个构造函数

转载 作者:行者123 更新时间:2023-12-02 18:45:54 24 4
gpt4 key购买 nike

我正在尝试理解右值引用。这是我到目前为止编写的代码:

class A {
public:
A(const char* str) {
std::cout << str;
}

A(A&& other) {
std::cout << "other";
}
};

int main() {
A m(A(A(A("hello"))));
}

输出仅为"hello" ,这让我很困惑。

A("hello")是传递给第二个构造函数的临时对象,但代码输出就像只调用了第一个构造函数。

我想这要么是编译器优化,要么我错过了有关构造函数和右值的一些细节。

最佳答案

您观察到的内容也称为 copy elision ,更准确地说:

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:

(...)

  • In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:

T x = T(T(f())); // only one call to default constructor of T, to initialize x

这正是你的情况。

请注意,从 C++17 开始,优化是强制的。对于 C++11 来说它是可选的,但您的编译器似乎还是应用了它。

关于C++只调用一个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67435394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com