#include <iostream>
#include <string>
usingnamespace std;
struct create_info {
string text;
};
struct window {
create_info c_info;
window() {}
};
template<typename wnd_t>
struct wnd {
wnd_t* impl;
wnd() {
impl = new wnd_t;
}
wnd(create_info& ci) { // plan 1
impl->c_info = ci;
}
};
int main() {
// usage 1
wnd<window> w1;
w1 = create_info(); // need to support this
cout << w1.impl->c_info.text << endl;
// usage 2
wnd<window> w2 = create_info();// also need to support this
cout << w2.impl->c_info.text << endl;
}
I need the wnd class support both usage 1/2, but the code crashes. From the debugger I see this line w1 = create_info();
creates a new instance of wnd, and in the constructor impl is used without being initialized.
Anyway to solve this?
well, since impl is not initialized, do initialize it before attempting impl->c_info
While you're at it, you could change its type to a better-behaved pointer, since otherwise you have more code to write (destructor, copy ctor, copy assignment at least)
That's because w2 = create_info(); creates and destroys a temporary in this case. You could add an assignment operator that takes a create_info on the right, if you need to avoid that temporary:
Although this is questionable usage: I would make the constructor from create_info explicit and disallow assignment from create_info altogether. Do you have a use for a default-constructed wnd?
At first I thought the wnd should have default create_info even if not explicitly constructed with a create_info, maybe it's not necessary:)
anyway the operator=() works fine