Say a given class A is defined with a public copy constructor and a private move constructor. If a function f returns an object of type A, and f is used to initialize a local instance of variable of type A, then by default (since the value returned is a rvalue) the compiler will try to use the move constructor. I believed it is sensible to expect the compiler to use the copy constructor once it detects that the move constructor is private, however to my surprise I received a compiler error stating that the move constructor is private. My question is as follows, given the following code:
#include<iostream>
using namespace std;
class A
{
friend A f();
public:
A(const A&) { cout << "copy\n"; }
private:
A() {}
A(A&&) { cout << "move\n"; }
};
A f()
{
A a;
return a;
}
int main()
{
A a = f();
}
How can I change the code (without changing A or f) so that I could initialize the variable in main using the copy constructor?
I would change the class since it's not sensible.
Alternatively derive from the class or wrap it.
If you just want a quick hack you can do
template< class Type >
Type& tempref( Type&& t ) { return t; }
then do
A a = tempref( f() )
Disclaimer: code not touched by compiler's hands.
The overload resolution is performed first, to select a function to call.
Access check is performed as a later step, checking if the selected function/constructor is possible to call.
This is done on purpose, so a private function is not called (because it is private). Having the compiler select another function to call in that case would not be productive.
Related
I read in http://www.cs.technion.ac.il/users/yechiel/c++-faq/init-lists.html
that using initializer lists is more efficient than doing assigment in the body of the constructor, because for example in Fred::Fred() { x_ = whatever; }
1) the expression whatever causes a separate, temporary object to be created, and this temporary object is passed into the x_ object's assignment operator. Then that temporary object is destructed at the ;
2)the member object will get fully constructed by its default constructor, and this might, for example, allocate some default amount of memory or open some default file
How can assigment cause the creation of some temporary object inside the constructor? That means that the Construtor would call itself: an infinite recursive call
I made the following piece of code to verify a copy of the object is created in the assigment process,hoping to see the additional creation and destruction of the temporary object but all I can see is the creating and destruction of the object I am creating in the main an of course no infinite recursive call.
How do I make sense of it and how can I modify the code to see the creation and destruction of the temporary object?
#include<iostream>
using namespace std;
class Base
{
private:
int c_var;
public:
Base( )
{ c_var=10;
cout <<"Constructor called"<<endl;
cout << "Value is " << c_var<<endl;
}
~Base()
{
cout <<"Destructor called"<<endl;
}
};
int main()
{
Base il;
}
How can assigment cause the creation of some temporary object inside the constructor? That means that the Construtor would call itself: an infinite recursive call
No. The text talks about calling the constructor of the member. With an int it doesn't matter too much, but consider:
struct foo {
foo() {
/* construct a foo, with expensive instructions */
std::cout << "default constructor";
}
foo(int x) {
/* also construct a foo */
std::cout << "constructor";
}
};
struct bar_wrong {
foo f;
bar_wrong() {
f = foo(42);
}
};
Members are initialized before the body of the constructor is executed. Hence the foo member of bar_wrong will first be default constructed (which is potentially expensive) just to be overwritten with the right instance later and creating a bar_wrong will print both outputs from foos constructors.
The correct way is
struct bar_correct {
foo f;
bar_correct() : f(42) {}
};
Because here foo is only initialized. Alternatively you can use in-class initializers:
struct bar_alternative {
foo f{42};
};
Here the compiler generated constructor is sufficient. It will use the in-class initializer to initialize f with 42.
#include <map>
class B {
public:
B() {}
};
class A {
public:
A(B b) {
}
};
int main()
{
std::map<int, A> list;
list[0] = A(B());
return 0;
}
The compiler complains that A should have a no-parameter constructor like this: A(){} because of the line list[0] = A(B());. I guess that list[0]; first createas a default A object and then executes the operator=(const A& a) on it so it can copy the A(B()); object.
However I don't want to create a default no-parameter constructor for my A class because it really should be initialized with a B object.
I managed to overcome this by doing
list.insert(std::pair<int, A>(0, A(B()));
Then I noticed that the following line:
A a = list[0];
wouldn't give any errors. For me, A a should create a default A oject using the empty A() constructor which does not exist, then the operator= would be applied. Why this line gives no error?
A a = list[0];
doesn't use a default constructor and the assignment operator. It calls the copy constructor for your class. The copy constructor is implicitly defined.
You get this error because map<>::operator[] instantiates an instance of the value-type (using the default constructor) if the indicated key is not found in the existing object. Due to this being a run-time test map<>::operator[] has to be able to perform that action even if the key is always in fact part of the object.
Take for example this code:
#include <type_traits>
#include <iostream>
struct Foo
{
Foo() = default;
Foo(Foo&&) = delete;
Foo(const Foo&) noexcept
{
std::cout << "copy!" << std::endl;
};
};
struct Bar : Foo {};
static_assert(!std::is_move_constructible_v<Foo>, "Foo shouldn't be move constructible");
// This would error if uncommented
//static_assert(!std::is_move_constructible_v<Bar>, "Bar shouldn't be move constructible");
int main()
{
Bar bar {};
Bar barTwo { std::move(bar) };
// prints "copy!"
}
Because Bar is derived from Foo, it doesn't have a move constructor. It is still constructible by using the copy constructor. I learned why it chooses the copy constructor from another answer:
if y is of type S, then std::move(y), of type S&&, is reference compatible with type S&. Thus S x(std::move(y)) is perfectly valid and call the copy constructor S::S(const S&).
—Lærne, Understanding std::is_move_constructible
So I understand why a rvalue "downgrades" from moving to a lvalue copying, and thus why std::is_move_constructible returns true. However, is there a way to detect if a type is truly move constructible excluding the copy constructor?
There are claims that presence of move constructor can't be detected and on surface they seem to be correct -- the way && binds to const& makes it impossible to tell which constructors are present in class' interface.
Then it occurred to me -- move semantic in C++ isn't a separate semantic... It is an "alias" to a copy semantic, another "interface" that class implementer can "intercept" and provide alternative implementation. So the question "can we detect a presence of move ctor?" can be reformulated as "can we detect a presence of two copy interfaces?". Turns out we can achieve that by (ab)using overloading -- it fails to compile when there are two equally viable ways to construct an object and this fact can be detected with SFINAE.
30 lines of code are worth a thousand words:
#include <type_traits>
#include <utility>
#include <cstdio>
using namespace std;
struct S
{
~S();
//S(S const&){}
//S(S const&) = delete;
//S(S&&) {}
//S(S&&) = delete;
};
template<class P>
struct M
{
operator P const&();
operator P&&();
};
constexpr bool has_cctor = is_copy_constructible_v<S>;
constexpr bool has_mctor = is_move_constructible_v<S> && !is_constructible_v<S, M<S>>;
int main()
{
printf("has_cctor = %d\n", has_cctor);
printf("has_mctor = %d\n", has_mctor);
}
Notes:
you probably should be able to confuse this logic with additional const/volatile overloads, so some additional work may be required here
doubt this magic works well with private/protected constructors -- another area to look at
doesn't seem to work on MSVC (as is tradition)
How to find out whether or not a type has a move constructor?
Assuming that the base class comes from the upstream, and the derived class is part of your application, there is no further decision you can make, once you decided to derive 'your' Bar from 'their' Foo.
It is the responsibility of the base class Foo to define its own constructors. That is an implementation detail of the base class. The same is true for the derived class. Constructors are not inherited. Trivially, both classes have full control over their own implementation.
So, if you want to have a move constructor in the derived class, just add one:
struct Bar : Foo {
Bar(Bar&&) noexcept {
std::cout << "move!" << std::endl;
};
};
If you don't want any, delete it:
struct Bar : Foo {
Bar(Bar&&) = delete;
};
If you do the latter, you can also uncomment the second static_assert without getting an error.
I don't understand why the compiler chooses the copy constructor of my Production class and has no other candidate functions.
I made a minimal example to demonstrate the error:
#include <string>
#include <typeindex>
#include <iostream>
struct DummyProduction {
};
struct Dep {
};
struct Pro {
};
class ModuleBase {
};
template<typename Production = DummyProduction>
class Provider {
public:
template<typename... Dependencies>
Provider(ModuleBase& module, Dependencies... args)
{
std::cout << "Provider called!" << std::endl;
}
Provider(const Provider&) = delete;
};
class TargetController : public ModuleBase,
public Provider<Pro>,
public Provider<>
{
public:
TargetController();
private:
Dep p;
};
TargetController::TargetController() :
ModuleBase(),
Provider<Pro>(*this, &p),
Provider<>(*this),
p()
{
}
int main()
{
TargetController x;
return 0;
}
I tried it with gcc and clang. Here is a link to the non working example: link.
For the Provider<Pro>(*this, p) the right constructor is called. But for the second example Provider<>(*this) the compiler tries to call the copy-constructor.
From what I understood from the Overload resolution page all functions that match the expressions are should get inside the candidate function set. But either the variadic constuctor is not inside the set for the Provider without dependencies or the compiler chooses the copy-constructor in spite of beeing deleted.
Is there a way to avoid this behaviour?
The fact that an function/method is deleted doesn't remove it from overload list.
And the copy constructor has higher priority over the template method (as it is not an exact match).
As workaround you may cast this to the expected type:
TargetController::TargetController() :
ModuleBase(),
Provider<Pro>(*this, p),
Provider<>(static_cast<ModuleBase&>(*this))
{
}
Demo
Templated constructors are never copy constructors. When you call base's constructor and pass it a reference to base (or a derived) the copy constructor is supposed to be called. The template isn't an option in that context.
Provider<>(*this)
Is such a context.
Worth noting that I believe VS still gets this wrong. In that compiler you have to cast to base& or it'll call the template.
My understanding of constructor chaining is that , when there are more than one constructors in a class (overloaded constructors) , if one of them tries to call another constructor,then
this process is called CONSTRUCTOR CHAINING , which is not supported in C++ .
Recently I came across this paragraph while reading online material.... It goes like this ...
You may find yourself in the situation where you want to write a member function to re-initialize a class back to default values. Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++. You could copy the code from the constructor in your function, which would work, but lead to duplicate code. The best solution in this case is to move the code from the constructor to your new function, and have the constructor call your function to do the work of initializing the data.
Does a member function calling the constructor also come under constructor chaining ??
Please throw some light on this topic in C++ .
C++11 allows constructor chaining (partially). This feature is called "delegating constructors". So in C++11 you can do the following
class Foo
{
public:
Foo(int a) : Foo() { _a = a; }
Foo(char* b) : Foo() { _b = b; }
Foo() { _c = 1.5; }
private:
int _a = 0;
char* _b = nullptr;
double _c;
};
However, there is a severe limitation that a constructor that calls another constructor is not allowed to initialize any other members. So you cannot do the following with a delegating constructor:
class Foo
{
public:
Foo(int a) : Foo(), _a(a) { }
Foo(char* b) : Foo(), _b(b) { }
Foo() { _c = 1.5; }
private:
int _a = 0;
char* _b = nullptr;
double _c;
};
MSVC++2013 gives compile error "C3511: a call to a delegating constructor shall be the only member-initializer" for the latter code example.
The paragraph basically says this:
class X
{
void Init(params) {/*common initing code here*/ }
X(params1) { Init(someParams); /*custom code*/ }
X(params2) { Init(someOtherParams); /*custom code*/ }
};
You cannot call a constructor from a member function either. It may seem to you that you've done it, but that's an illusion:
class X
{
public:
X(int i):i(i){}
void f()
{
X(3); //this just creates a temprorary - doesn't call the ctor on this instance
}
int i;
};
int main()
{
using std::cout;
X x(4);
cout << x.i << "\n"; //prints 4
x.f();
cout << x.i << "\n"; //prints 4 again
}
That's not what the text says. It's suggesting your constructor call a member function which is normal and legal. This is to avoid explicitly calling the ctor again and to avoid duplicating code between your ctor and reset function.
Foo::Foo() {
Init();
}
void Foo::Reset() {
Init();
}
void Foo::Init() {
// ... do stuff ...
}
I'm not sure if it (calling a constructor from a member function) will work or not, but it's a bad practice. moving the initialize code to a new function is the logic way.
Basically saying, Don't call the constructor unless you constructing...
when we call constructor from a member function, then it will temporary create a object of its type.
in case if we are calling in derived class function then all the parent constructors are also gets executed and destroyed using destructor once function goes out of scope.
its not a Good Practice to call the constructors in member functions since it creates objects of every class derived.