隐式调用复制构造函数?
Copy constructor implicitly called?
我有以下 class,同时定义了普通构造函数和复制构造函数。
#include <iostream>
class Bla
{
public:
Bla()
{
std::cout << "Normal Constructor Called\n";
}
Bla(const Bla& other)
{
std::cout << "Copy Constructor Called\n";
}
};
int main()
{
Bla a = Bla(); // prints Normal Constructor
}
在主函数中,它按我的预期打印了普通构造函数,并且只打印了普通构造函数。但是,如果我将复制构造函数设为 class 的私有成员,编译器会给出错误
error: ‘Bla::Bla(const Bla&)’ is private within this context
从外观上看,似乎调用了复制构造函数,但我没有看到从中打印出任何内容。复制构造函数是否被隐式调用?这是怎么回事?
在 C++17 之前,复制操作可能是 elided,但复制构造函数仍然需要存在和访问。
This is an optimization: even when it takes place and the copy/move (since C++11)
constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:
自 C++17 起,由于强制复制省略,不再存在此类问题。
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:
我有以下 class,同时定义了普通构造函数和复制构造函数。
#include <iostream>
class Bla
{
public:
Bla()
{
std::cout << "Normal Constructor Called\n";
}
Bla(const Bla& other)
{
std::cout << "Copy Constructor Called\n";
}
};
int main()
{
Bla a = Bla(); // prints Normal Constructor
}
在主函数中,它按我的预期打印了普通构造函数,并且只打印了普通构造函数。但是,如果我将复制构造函数设为 class 的私有成员,编译器会给出错误
error: ‘Bla::Bla(const Bla&)’ is private within this context
从外观上看,似乎调用了复制构造函数,但我没有看到从中打印出任何内容。复制构造函数是否被隐式调用?这是怎么回事?
在 C++17 之前,复制操作可能是 elided,但复制构造函数仍然需要存在和访问。
This is an optimization: even when it takes place and the copy
/move (since C++11)
constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:
自 C++17 起,由于强制复制省略,不再存在此类问题。
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: