If we do not want the copy to happen for some classes, we can mark the copy constructor as deleted using =delete. For example,
#include <iostream>
class Point
{
int m_x{};
int m_y{};
public:
Point() = default;
Point(int x, int y)
: m_x{x}, m_y{y}
{
std::cout << "Constructing using Point(" << x << ", " << y << ")\n";
}
// copy constructor
Point(const Point &obj) = delete;
void print() const
{
std::cout << "{" << m_x << ", " << m_y << "}\n";
}
};
Point createPoint(int a, int b)
{
Point x{a, b};
return x;
}
int main(int argc, char const *argv[])
{
Point y{createPoint(1, 2)};
return 0;
}When we run this program, it should fail saying that deleted copy constructor is called for returning x from function createPoint.
copy_constructor.cpp: In function 'Point createPoint(int, int)':
copy_constructor.cpp:39:12: error: use of deleted function 'Point::Point(const Point&)'
39 | return x;
| ^
copy_constructor.cpp:18:5: note: declared here
18 | Point(const Point &obj) = delete;
| ^~~~~
copy_constructor.cpp:39:12: note: use '-fdiagnostics-all-candidates' to display considered candidates
39 | return x;