gpt4 book ai didi

c++ - 使用赋值运算符构造对象

转载 作者:行者123 更新时间:2023-11-30 02:23:00 25 4
gpt4 key购买 nike

我想知道使用赋值运算符构造对象是否有效,在我看到这个问题之前从未见过:

return by value calls copy ctor instead of move

精简示例代码:

class A
{
public:
int x;
A(int _x):x(_x){ std::cout << "Init" << std::endl;}
void Print() { std::cout << x << std::endl; }
A& operator = ( const int ) = delete;
};

int main()
{
A a=9;
a.Print();
}

正在写

A a(9);
A a{9};
A a=9;

都一样吗?

最佳答案

这与赋值运算符无关,它是初始化,更准确地说是copy initialization ,它只在初始化程序中使用等号。

when a named variable (automatic, static, or thread-local) of a non-reference type T is declared with the initializer consisting of an equals sign followed by an expression.

对于 A a = 9;,将调用适当的构造函数(即 A::A(int))来构造 a1

A a(9);direct initialization , A a{9};direct list initialization (C++11 起),它们都会导致调用 A::A(int) 来为这种情况构造对象。 2


1 在 C++17 之前,概念上仍然需要适当的移动/复制构造函数。即使它可能被优化掉,但仍然必须可以访问。从 C++17 开始,这不再是必需的。

2 请注意,这些初始化样式之间仍然存在细微差别,在某些特殊情况下它们可能会导致不同的效果。

关于c++ - 使用赋值运算符构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46628908/

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