Reputation: 7961
I am trying to create a class instance with no default constructor from another class' constructor but not passing them as class initializers. Here is a sample code of what I am trying to do:
class Device {
public:
Device(const PhysicalDevice& device) { ... }
};
class Renderer {
public:
Renderer() {
auto physicalDevice = getPhysicalDevice();
device = Device(physicalDevice); // <-- this causes me a problem
}
PhysicalDevice getPhysicalDevice();
Device device;
};
Because I create a Device object and assign it to the member variable device
, I am copying the temporary object to member variable, which means that temporary object needs to be destroyed.
Is there a way I can get rid of the temporary object and just initialize device directly?
Upvotes: 0
Views: 76
Reputation: 310960
You can write using a mem-initializer list like:
class Renderer {
public:
Renderer() : device( getPhysicalDevice() ) {
}
PhysicalDevice getPhysicalDevice();
Device device;
};
As for your constructor definition then in this statement:
device = Device(physicalDevice);
it is supposed that the data member device was already created using the default constructor (that was not defined) before passing the control to the constructor body. So the compiler issues an error.
Upvotes: 3
Reputation: 409166
Use an initializer list for the constructor:
Renderer()
: device{ getPhysicalDevice() }
{
/* Empty */
}
This will be used to initialize the device
object, rather than having it be default-initialized and then assign to it.
Upvotes: 2