问题
Objects in C++ can be created using the methods listed below(that I am aware of):
Person p;
or
Person p("foobar");
or
Person * p = new Person();
Then, why does not the Samsung Bada IDE allow me to do the first two methods? Why do I always have to use pointers? I am ok with using pointers and all, just that I want to know the fundamental reason behind the style.
Sample code from Bada API reference.
// Create a Label
Label *pLabel = new Label();
pLabel->Construct(Rectangle(50, 200, 150, 40), L"Text");
pLabel->SetBackgroundColor(Color::COLOR_BLUE);
AddControl(*pLabel);
I modified and tried using the code below. Although it compiles and the app runs, the label does not show up on the form.
// Create a Label
Label pLabel();
pLabel.Construct(Rectangle(50, 200, 150, 40), L"Text");
pLabel.SetBackgroundColor(Color::COLOR_BLUE);
AddControl(pLabel);
Note : Rectangle class which is used creates an object on the fly without pointer. How is it different from Label then? Its confusing :-/
回答1:
In this code:
// Create a Label
Label pLabel;
pLabel.Construct(Rectangle(50, 200, 150, 40), L"Text");
pLabel.SetBackgroundColor(Color::COLOR_BLUE);
AddControl(pLabel);
the label object is destroyed when it goes out of scope and hence it fails to show up on the form. It is unfortunate that the AddControl
method takes a reference as that implies that the above should work. Using:
Label *pLabel = new Label();
works because the destructor is not called by default when the pLabel
variable goes out of scope.
回答2:
Note that Bada documentation says this
All containers and controls must be created on the device heap memory. When an application terminates, the bada platform deletes the frame control and its descendants. Furthermore, the platform frees the heap memory that has been allocated to the application.
Your code may run fine because it ignores the call to AddControl because it detected that the control was not allocated in the heap space. In that case AddControl should have returned an error code.
To get a correct Bada code, one needs to write something like:
result MySample::OnInitializing() {
result r = E_SUCCESS;
std::auto_ptr<Label> pLabel(new Label);
if (pLabel.get() != null && E_SUCESS == pLabel->Construct(Rectangle(50, 200, 150, 40), L"Text"))
{
pLabel->SetBackgroundColor(Color::COLOR_BLUE);
r = AddControl(*pLabel);
pLabel.release();
}
else
{
r = E_FAILURE;
}
return r;
}
Following such coding guidelines ensures that your application will be able to escalate any issues while initializing UI except if the issue happens whiele executing OnAppInitializing.
回答3:
Visitor nailed it in his comment; Bada uses C++ techniques pioneered in the mid-nineties by Symbian. They're utterly outdated today. Don't take it too seriously, you can't really expect Samsung to put their top-rate people on such a doomed project. Those will be working on their Android line.
来源:https://stackoverflow.com/questions/7481968/samsung-bada-development-without-using-pointers