Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am writing code C++ code in Xcode. At an instance I'm making sure that all fields are valid.
SomeClass *myclass = new SomeClass();
std::string myString;
if ( (myClass) && (myString.c_str)) {
return true;
} else {
return false;
}
Should i be checking for testString.c_str? Does it makes sense?
The default behavior of the new() operator is to either return the new object, or throw an exception if memory allocation failed. So, you don't need to check if myClass is NULL, unless you set the flags to change the behavior or implemented your own new() operator for your class.
Also, the extra brackets around myClass are not necessary. A better way to express what you want to check would be
if ((myClass != nullptr) &&
Then, you are currently testing if the address of the method c_str() in the std::string class is not NULL. Not want you want to do, I guess.
First, you would need to write myString.c_str(). Then, this method never returns a NULL pointer, what it can return is an empty C string. But this is better tested with std::string::empty(), so your check would look like this:
if (myString.empty()) {
return false;
} else {
return true;
}
which can of course be shortened into
return !myString.empty();
Finally: If you have this code in a function/method: Who deletes your new SomeClass object?
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm currently getting this error:
'User::User(const User&)': attempting to reference a deleted function
The program passes a string value of an object into the class.
User Constructor:
User::User(string s){
int size = s.length() + 1;
char* cstr = new char[size];
strcpy_s(cstr, size, s.c_str());
user.Parse(cstr);
}
Main Loop:
int main(){
//json equals something similar to this: "{\"body:{[{"user":1},{"user":1},{"user":1}]}\"}";
const char * json;
Document d;
d.Parse(json);
if (d.HasMember("body")) {
if (d["body"].IsArray()) {
for (SizeType i = 0; i < d["body"].Size(); i++) {
string json = getJsonString(d["body"][i]);
User u = User(json); \\this is where the error point to
this->users.push_back(u);
}
}
}
}
getJsonString function:
string getJsonString(Value& value) {
StringBuffer buffer;
buffer.Clear();
Writer<StringBuffer> writer(buffer);
value.Accept(writer);
return string(buffer.GetString());
}
I search for a lot of explanation on this error but nothing seems to make sense to me. I think it has something to do with the vector array however it doesn't make sense to me as I'm not using a pointer or reference for any of the user value. It seems to point to the constructor however no pointer or reference is being passed through. I through by returning the string of the json, I wasn't using a pointer but maybe I actually am? I would be grateful for any explanation to what I am doing wrong.
User is not copyable; this means that:
User::User(const User&) (copy constructor) is private
or deleted (= delete;)
or deleted implicitly (e.g. class has non-copyable members, or inherits from a non-copyable class). Thank you Yksisarvinen for the comment
This means you are not allowed to create a new User from another one.
Then, if you want to store User objects in a vector (as you are "apparently" trying to do in your post, I say "apparently" because the posted code does not compile, I dunno who is this) you cannot store them by value, as the vector contained needs an accessible copy constructor.
See std::vector:
T must meet the requirements of CopyAssignable and CopyConstructible.
However, you can store them as pointers:
std::vector<std::shared_ptr<User>> users;
users.push_back( std::shared_ptr<User>( new User( json ) );
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm working on a Boolean function in C/C++ that verifies multiple conditions (that are Boolean functions themselves) and only returns true if all of them are true.
Time ago I started using Guard Clauses instead of nested ifs, even though it required having multiple returns like follows:
bool foo(){
//some initialization
if( !condition_1() ){
return false;
}
if( !condition_2() ){
return false;
}
...
if( !condition_n() ){
return false;
}
return true;
}
But now I'm asking my self if is it a good alternative to use only one return with Boolean logic, for example:
bool foo(){
//some initialization
return condition_1() && condition_2() && ... && condition_n() ;
}
I don't have any code to run after the guards and there are only a few of them,
so the return statement is not that crowded and the code is not difficult to read. The idea is to avoid nested ifs and use only one exit point in my function.
I tested the code and it works fine, even if condition_1() makes some changes in condition_2(). So I understand that the guard clause code and this version are equivalent and the execution order is maintained form left to right. Is that correct? Are there any hidden differences that make the two versions not 100% equivalent?
Thanks!
You new approach is good, depending if you want to do more than just concat bool operations, it could be useful for maintenance and readability to use a local.
bool foo(){
//some initialization
bool returnCondition = condition_1() &&
condition_2() &&
condition_3() &&
.... &&
condition_n();
return returnCondition;
}
By the way, there is nothing such as the best option.
Indeed, if your objective is code obfuscation, your first option is better than the 2nd.
Technically the two methods you use are correct in case of the functions condition_n() is used only for checking.
But if you need to change something inside them based on a condition of something it will be a problem.
The Best Practice for writing a function body is as follows:
define the default return value
some processing
return the result
Let's rewrite the above function :
bool foo(){
//some initialization
bool ret = true;
if(condition_1() == false){
ret = false;
}
else if(condition_2() == false){
ret = false;
}
...
else if(condition_n() == false){
ret = false;
}
return ret;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In C++, we have to allocate/deallocate memory manually. In my loader function, this becomes a knotty problem. It loads data from a bunch of files containing different formats of data. And loading one file means doing a lot allocation in different places. The failure of one loading cause a total failure, which means I have to rollback all the allocation & initializition before. But the current design, using a lot of singletons, globals etc. doesn't provides a convenient way to rollback. I need suggestions or code samples to follow. Please help.
I guess build my own allocator is a good solution. But it doesn't works for foreign libraries used in my project who use their own allocators.
Please, don't say using smart pointers. It really means making my project more complicated.
So, some code is provided here. My project is a small interpreter. The language it interprets is XML. A complete program consists of several XML files, describing different data the program is using.
extern std::map<std::string, Sub *> g_subMap;
// ...
// load every `subroutines' defined in XML
// so what should I do if one of them fails to load?
XMLElement *pRootElem = doc.RootElement();
for (XMLElement *pChild1 = pRootElem->FirstChildElement(); pChild1; pChild1 = pChild1->NextSiblingElement()) {
if (stricmp(pChild1->Value(), "sub") == 0) {
const char *name = pChild1->Attribute("name");
Sub *pSub = new Sub();
bool success = pSub->Load(pChild1);
// ?
g_subMap[name] = pSub;
}
}
From the code you shared, here's a simple update.
Use a temp map to handle the loading. The destructor of subs will release the reference when it goes out of scope. If it hasn't been copied over to g_subMap, as in the success case, then the temporary loaded "Sub" objects are deleted for you.
map<string, shared_ptr<Sub>> subs;
bool success = true;
for (XMLElement *pChild1 = pRootElem->FirstChildElement(); pChild1; pChild1 = pChild1->NextSiblingElement())
{
if (stricmp(pChild1->Value(), "sub") == 0)
{
string name = pChild1->Attribute("name");
shared_ptr<Sub> spSub = shared_ptr<Sub>(new Sub());
subs[name] = spSub;
success = spSub->Load(pChild1);
if (success == false)
{
break;
}
}
}
if (success)
{
// migrate our temp map of "subs" into g_subMap, which has
// also been converted to be a map of shared_ptr<Sub>
for (auto itor = subs.begin(); itor != subs.end(); itor++)
{
g_subMap[itor->first] = itor->second; // shared_ptr reference count gets incremented on assignment
}
}
// when "subs" goes out of scope it will decrement the reference count on each item in the map. If the item wasn't copied over g_subMap, it gets deleted.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'd like to make one directional list of objects in C++. I've got 3 classes: BasicMiachine,Desktop,Laptop. Two last classses extends BasicMachine. What I want to do is make a list of object (Desktop,Laptop) using only one list. In Basic Class which is abstract class (because I have declare one method as virtual) I have a field which is a pointer to next object is a BasicClass type. Below is my code:
int main () {
BasicClass* headList= NULL;
BasicClass* iterator = NULL;
while(....)
{
switch(.....){
case 1:
addNewComputer(headList,iterator,numberOfObjects);
break;
}
}
void static addNewComputer(BasicClass* headList, BasicClass* iterator,short numberOfObjects)
{
short choice;
cout<<"What is your machine?"<<endl<<"1) Desktop or2) Laptop"<<endl;
cout<<"Your choice: "; cin>>choice;
if(choice== 1)
{
//Add some data to variables// ....//
if(numberOfObjects == 0)
{
headList = new Desktop(wysokosc,dlugosc,szerokosc, taktowanieProcesora, numerIdentyfikacyjny, typProcesora, nazwaWSieci,ID);
iterator= headList ;
iterator->nextObject = NULL;
}
else
{
BasicClass* tmpIterator= NULL;
tmpIterator= headList ;
tmpIterator->nextObject = new Desktop(wysokosc,dlugosc,szerokosc, taktowanieProcesora, numerIdentyfikacyjny, typProcesora, nazwaWSieci,ID);
tmpIterator= pomocniczyWskaznik -> nextObject;
tmpIterator->nextObject = NULL;
}
}
else if(choice == 2)
{
//It is the same as above but I add here a La
}
};
After I add one and second computer I got an error like: "Access violation writing location 0x00000050." Is it a problem with pointers? I use BasicClass type pointers to hold both objects (Desktop, Laptop).
You make the classic mistake of passing pointers by value instead of by reference.
Change addNewComputer to e.g.
void static addNewComputer(BasicClass*& headList, BasicClass*& iterator,short numberOfObjects)
and things should work better.
I suggest you to take a look to standard containers. Anyway, the problem is that your are passing pointers by value, so when you call "new" the pointer inside addNewComputer() points to a new memory direction and when the function returns, headList and iterator are null (notice the memory leak issue). To solve your problem, you need to pass headList and iterator by reference i.e.
void static addNewComputer(BasicClass*& headList, BasicClass*& iterator,short numberOfObjects)
Hope this help.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have seen many exception handling mechanisms where they simply weren't necessary. A lot of the times the problem could have been solved in a much cleaner way using simple if statements.
For example, things like:
Invalid input
Division by zero
Wrong type
Container range check
Null pointer
Uninitialized data
... and so on.
Could someone provide an example where it would be a better approach to handle exceptions?
Exceptions become more important as your program size grows.
With a simple application return codes are probably fine. But when an error condition needs to bubble up a couple levels of the stack before being handled, it starts to make sense to use exceptions instead of passing error codes from every function.
Also, when a method already returns a value, it may not be practical or possible to return an error code from the function as well.
Sometimes using exception is cleaner. In function foo thanks to exception throwing in check function you can avoid checking what check returns what makes this function simpler:
#include<iostream>
using namespace std;
class A{
public:
int a_foo(int index){return _tab[index];}
private:
static int _tab[3];
};
int A::_tab[3]={1,2,3};
void check(int index)
{
if (index < 0 || index > 2)
throw string("invalid index");
}
void foo(A a, int index){
check(index);
cout << a.a_foo(index) << endl;
}
int main()
{
try
{
A a;
foo(a,4);
}
catch(string ex)
{
cerr << ex <<'\n';
}
}
I would use it when the consequence of some unexpected 'event' is inability for application to continue running. When it happens and you catch it, report it nicely and close the application (or whatever you think you should do in that case).