c++中复制初始化使用什么特殊成员函数?
What special member function is used for copy initialization in c++?
我正在测试 C++ class 初始化。
class Point
{
private:
int x,y;
public:
Point() = delete;
Point(int a):x(a), y(0) { std::cout << "Conversion" << std::endl;}
Point(const Point&) { std::cout << "Copy constructor" << std::endl;}
//Point(const Point&) = delete;
Point& operator=(const Point&) = delete;
Point(Point&&) = delete;
Point& operator=(Point&&) = delete;
};
int main()
{
Point p1(5); //case1
Point p2 = 5; //case2
return 0;
}
在上面的代码中,一开始我以为 case1/2 的转换构造函数会将“5”转换为临时对象。然后,我预计必须使用复制构造函数来初始化 p1 和 p2。但是,事实并非如此。
当我 运行 这段代码时,我在控制台中只看到两条“转换”消息。没有“复制构造函数”消息。
尽管我删除了所有复制构造函数、移动构造函数、复制赋值运算符和移动赋值运算符,但这段代码运行良好。
如果你告诉我在为“5”创建临时对象后将使用什么特殊成员函数进行初始化,我将不胜感激,
我正在使用带有 std=c++17 选项的 g++ 编译器。
案例一
在情况 1 中,使用了 转换构造函数 ,因为您提供了一个可以将 int
转换为 Point
的构造函数。这就是为什么这个构造函数被称为转换构造函数。
案例二
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.
在情况 2 中,即使您 delete
copy/move 构造函数也只会使用转换构造函数。这是由于 mandatory copy elison(在 C++17 中),如上所述。
我正在测试 C++ class 初始化。
class Point
{
private:
int x,y;
public:
Point() = delete;
Point(int a):x(a), y(0) { std::cout << "Conversion" << std::endl;}
Point(const Point&) { std::cout << "Copy constructor" << std::endl;}
//Point(const Point&) = delete;
Point& operator=(const Point&) = delete;
Point(Point&&) = delete;
Point& operator=(Point&&) = delete;
};
int main()
{
Point p1(5); //case1
Point p2 = 5; //case2
return 0;
}
在上面的代码中,一开始我以为 case1/2 的转换构造函数会将“5”转换为临时对象。然后,我预计必须使用复制构造函数来初始化 p1 和 p2。但是,事实并非如此。 当我 运行 这段代码时,我在控制台中只看到两条“转换”消息。没有“复制构造函数”消息。
尽管我删除了所有复制构造函数、移动构造函数、复制赋值运算符和移动赋值运算符,但这段代码运行良好。
如果你告诉我在为“5”创建临时对象后将使用什么特殊成员函数进行初始化,我将不胜感激,
我正在使用带有 std=c++17 选项的 g++ 编译器。
案例一
在情况 1 中,使用了 转换构造函数 ,因为您提供了一个可以将 int
转换为 Point
的构造函数。这就是为什么这个构造函数被称为转换构造函数。
案例二
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.
在情况 2 中,即使您 delete
copy/move 构造函数也只会使用转换构造函数。这是由于 mandatory copy elison(在 C++17 中),如上所述。