Copy constructor is implicitly declared as deleted...

If I try to compile the object below I get the error:
1
2
note: ‘constexpr Object::Object(const Object&)’ is implicitly declared as deleted because
‘Object’ declares a move constructor or move assignment operator


If I put in a move and copy constructor, that fixes the error, but I don't understand why the error exists. Can someone explain why the error exists?

1
2
3
4
5
6
7
8
9
10
11
12
13
class Object
{
	private:
	int number;

	public:
	Object();

	Object& operator=(const Object& s);
	Object& operator=(Object&& s);

};
Last edited on
Can someone explain why the error exists?

The short answer: Because the standard requires it.

See http://stackoverflow.com/questions/31838748/generated-copy-and-move-operators
This would compile cleanly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

struct Segment {} ;

class Object
{
    private:
	int number;

	public:
	Object() {}

	Object& operator=(const Segment&) { return *this ; }
	Object& operator=(Segment&&) { return *this ; }

};

int main()
{
    Object x ;
    Object y(x) ;
    std::cout << std::addressof(x) << ' ' << std::addressof(y) << '\n' ;
}

http://coliru.stacked-crooked.com/a/7c4320da96a3963b

This would not:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class Object
{
    private:
	int number;

	public:
	Object() {}

	Object& operator=(const Object&) { return *this ; }
	Object& operator=(Object&&) { return *this ; } // move-assignment operator

};

int main()
{
    Object x ;
    Object y(x) ; // *** error: implicitly deleted copy constructor
    std::cout << std::addressof(x) << ' ' << std::addressof(y) << '\n' ;
}

http://coliru.stacked-crooked.com/a/25d85e929ffe3ef5

More information: http://www.stroustrup.com/C++11FAQ.html#default2
@JLBorges
Yea, sorry, I meant to have Object as parameter to operator=, not segment. I copied and pasted a more specific code and decided to change the name and forgot to change the parameter.
Last edited on
Topic archived. No new replies allowed.