C++ Break out of a function at an early stage - c++

I have two questions.
The first is about working with functions. I need to break out of a function at an early stage under a condition.
For example:
std::string concat(std::string& x, std::string& y, std::vector<std::string>& vec)
{
if (atoi(x.c_str()) < 0)
{
return;
}
else {
std::string concatStr = y + x;
top_back(vec);
top_back(vec);
return concatStr;
}
}
As you can see, the function must return a string, but if the string x(which i of course convert to int) is less than 0, then I theoretically should break out of the function.
The problem with writing just return; is that the compiler tells me that it needs to return a value.
The second question is how can I remove the last line from the console?
That's connected with the first question, as someone suggested that return "";
is a good workaround, but it writes a blank space into the console, which in my case with the program I'm writing is not good and causes problems.

If you can compile using C++17 you can use std::optional to allow you to optionally return something from the function. We would rewrite your function to
std::optional<std::string> concat(std::string& x, std::string& y, std::vector<std::string>& vec)
{
if (atoi(x.c_str()) < 0)
{
return {};
}
else
{
std::string concatStr = y + x;
top_back(vec);
top_back(vec);
return concatStr;
}
}
And then in the call site you can use it like
auto ret = concat(some, stuff, here)
if(ret) // only print if ret actually holds a string
std::cout << *ret;
Alternatively you could use a unique_ptr and return an empty pointer if there is no result. The function would change to
std::unique_ptr<std::string> concat(std::string& x, std::string& y, std::vector<std::string>& vec)
{
if (atoi(x.c_str()) < 0)
{
return {};
}
else
{
std::string concatStr = y + x;
top_back(vec);
top_back(vec);
return std::make_unique<std::string>(concatStr);
}
}
but the call site would remain the same.
Lastly if a blank string is never going to be a valid return from the function you could just return that and handle it in the call site like
std::string concat(std::string& x, std::string& y, std::vector<std::string>& vec)
{
if (atoi(x.c_str()) < 0)
{
return {};
}
else
{
std::string concatStr = y + x;
top_back(vec);
top_back(vec);
return concatStr;
}
}
int main()
{
//...
auto ret = concat(some, stuff, here)
if(ret != "") // only print if ret actually holds a string
std::cout << ret;
//...
}

Because you are not satisfied with C++17 solutions, it is possible to write your own std::optional implementation.
template<typename T>
class Optional
{
bool m_HasValue;
T m_Object;
public:
Optional() : m_HasValue(false){};
Optional(T&& Object) : m_HasValue(true), m_Object(std::forward<T>(Object)){};
operator T&(){return m_Object;}
operator bool(){return m_HasValue;}
T& operator*(){return m_Object;}
};
This is a very simplified version of std::optional, but it will fulfill your needs.
Its usage remains the same as in this post above.
using std::string;
Optional<string> DoSomething(string Input)
{
if(Input == "dontprocessme")
return {}
// ... otherwise process the string
string Output;
// blah blah
return Output;
}
// ...
auto RetString = DoSomething("processme");
if(RetString)
std::cout << *RetString;

Related

C++ Use Function Preconditions Or Wrapper Classes with Invariants?

I find myself writing a lot of functions that begin with many preconditions, and then I have to figure out how to handle all the invalid inputs and write tests for them.
Note that the codebase I work in does not allow throwing exceptions, in case that becomes relevant in this question.
I am wondering if there is any C++ design pattern where instead of having preconditions, input arguments are passed via wrapper classes that guarantee invariants. For example suppose I want a function to return the max value in a vector of ints. Normally I would do something like this:
// Return value indicates failure.
int MaxValue(const std::vector<int>& vec, int* max_value) {
if (vec.empty()) {
return EXIT_FAILURE;
}
*max_value = vec[0];
for (int element : vec) {
if (element > *max_value) {
*max_value = element;
}
}
return EXIT_SUCCESS;
}
But I am wondering if there is a design pattern to do something like this:
template <class T>
class NonEmptyVectorWrapper {
public:
static std::unique_ptr<NonEmptyVectorWrapper>
Create(const std::vector<T>& non_empty_vector) {
if (non_empty_vector.empty()) {
return std::unique_ptr<NonEmptyVectorWrapper>(nullptr);
}
return std::unique_ptr<NonEmptyVectorWrapper>(
new NonEmptyVectorWrapper(non_empty_vector));
}
const std::vector<T>& vector() const {
return non_empty_vector_;
}
private:
// Could implement move constructor/factory for efficiency.
NonEmptyVectorWrapper(const std::vector<T>& non_empty_vector)
: non_empty_vector_(non_empty_vector) {}
const std::vector<T> non_empty_vector_;
};
int MaxValue(const NonEmptyVectorWrapper<int>& vec_wrapper) {
const std::vector<int>& non_empty_vec = vec_wrapper.vector();
int max_value = non_empty_vec[0];
for (int element : non_empty_vec) {
if (element > max_value) {
max_value = element;
}
}
return max_value;
}
The main pro here is that you avoid unnecessary error handling in the function. A more complicated example where this could be useful:
// Finds the value in maybe_empty_vec which is closest to integer n.
// Return value indicates failure.
int GetValueClosestToInt(
const std::vector<int>& maybe_empty_vec,
int n,
int* closest_val);
std::vector<int> vector = GetRandomNonEmptyVector();
for (int i = 0; i < 10000; i++) {
int closest_val;
int success = GetValueClosestToInt(vector, i, &closest_val);
if (success) {
std::cout << closest_val;
} else {
// This never happens but we should handle it.
}
}
which wastefully checks that the vector is non-empty each time and checks for failure, versus
// Returns the value in the wrapped vector closest to n.
int GetValueClosestToInt(
const NonEmptyVectorWrapper& non_empty_vector_wrapper,
int n);
std::unique_ptr<NonEmptyVectorWrapper> non_empty_vector_wrapper =
NonEmptyVectorWrapper::Create(GetRandomNonEmptyVector());
for (int i = 0; i < 10000; i++) {
std::cout << GetValueClosestToInt(*non_empty_vector_wrapper, i);
}
which can't fail and gets rid of the needless input checking.
Is this design pattern a good idea, is there a better way to do it, and is there a name for it?

Accessing a set of pointers

Here is my code:
class obj140{
public:
int x;
explicit obj140(int y):x(y){ }
bool operator<(const obj140& rhs) const{
return x < rhs.x;
}
};
int main() {
obj140 * wtf = new obj140[5] {obj140(1),obj140(1),obj140(3),obj140(4),obj140(5)};
std::set<obj140> orm(wtf,wtf+5);
}
Is this possible? like copying pointers to a set? I have no errors but I have no idea on how to access it though.
How do i print out the values from orm set?
I modified your code slightly to make what's going on easier to see and as an example of one way to get a look at the items stored in the set.
class obj140
{
public:
int x;
explicit obj140(int y) :x(y)
{
}
bool operator<(const obj140& rhs) const
{
return x < rhs.x;
}
void print() const
{
std::cout << x << std::endl;
}
};
int main()
{
obj140 * wtf = new obj140[5]
{ obj140(1), obj140(1), obj140(3), obj140(4), obj140(5) };
std::set<obj140> orm(wtf, wtf + 5);
for (auto it = orm.begin(); it != orm.end(); ++it)
{
it->print();
}
delete[] wtf; //edit. Forgot to clean up the pointer.
return 0;
}
Output:
1
3
4
5
What you are doing works and loaded the set. Since sets only store unique values (and order them, which makes for a great quickie sort if you need one) the second add of obj140(1) got discarded.

Check for changes in POD variables

I'm looking for an efficient way to check if a POD variable is altered between two cycles. I've come up with this solution:
class Foo {
public:
template<typename T>
bool isChanged(T& entry);
void endCycle();
private:
std::map<void*,size_t> entryMap; // <Address orig.,Size>
std::map<void*,void*>oldVals; // <Address orig., Address cpy.>
};
template<typename T> bool Foo::isChanged(T& entry)
{
entryMap[&entry] = sizeof(T);
if(oldVals[&entry] == NULL)
return false;
if(memcmp(&entry, oldVals[&entry], entryMap[&entry]))
return true;
else
return false;
}
void Foo::endCycle()
{
// Copy all the bytes to save them for the next cycle
for( std::map<void*,size_t>::iterator entryIt = entryMap.begin();
entryIt != entryMap.end();
++entryIt)
{
if(oldVals[entryIt->first] == NULL)
oldVals[entryIt->first] = malloc(entryIt->second);
memcpy(oldVals[entryIt->first], entryIt->first, entryIt->second);
}
}
Now i can use it like this:
Foo gBar;
void aFunction()
{
int ar;
char ba[3][3];
// Some code where ar and ba are filled
if(gBar.isChanged(ar))
// Do Something
if(gBar.isChanged(ba))
// Do Something
gBar.endCycle();
}
Is this an efficient way? My goal was a method which is very easy to use inside various cyclically called functions. I cleaned all the init and free logic from the code. Any suggestions? I especially don't like the oldshool malloc, memcpy and memcmp stuff but i don't know any other way how to do it.
Edit: Found a good solution based on Red Alerts suggestions.
I think you can use templates a little more effectively here.
template <typename T>
class Foo
{
public:
static std::map<T*, T> values;
static bool isChanged(T& entry)
{
auto it = values.find(&entry);
if(it == values.end())
{
values[&entry] = entry;
}
else if(entry != it->second)
{
it->second = entry;
return true;
}
return false;
}
};
template <typename T>
std::map<T*, T> Foo<T>::values;
int main() {
int ar = 3;
cout << Foo<int>::isChanged(ar) << endl; // 0
ar = 4;
cout << Foo<int>::isChanged(ar) << endl; // 1
for(auto& value : Foo<int>::values)
cout << value.second << endl; // 4
return 0;
}
This way you get one map per type, and you don't have to worry about inadvertently messing up an alias. You do need to define operator != and have a working copy constructor for your types, but that is much better than blindly using memcmp and memcpy.
You can also make further template specializations for arrays if you need to compare those (will be a bit more code, but nothing very complicated)
Edit: To get you started, this is what your template signature should look like:
template<class T, size_t N> bool isChanged(T(&entry)[N]); //will be called for stack allocated arrays
Or you can use char* to alias all of your values. This will let you use a single map for everything (like you were doing before, but this has no memcpy/memcmp). It will only work for POD. We could manually call the destructor when overwriting the buffer, but since there is no good way to do this in the class's destructor, it's probably best to leave out heap allocated data altogether.
class Foo
{
std::map<char**, char*> values;
public:
~Foo()
{
for(auto& value : values)
{
delete[] value.second;
}
}
template<typename T> bool isChanged(T& entry)
{
char** addr = reinterpret_cast<char**>(&entry);
auto it = values.find(addr);
if(it == values.end())
{
alignas(T) char* oldBuf = new char[sizeof(T)];
T* oldEntry = new(oldBuf) T;
*oldEntry = entry;
values[addr] = oldBuf;
}
else if(entry != *(reinterpret_cast<T*>(it->second)))
{
T* oldEntry = new(it->second) T;
*oldEntry = entry;
return true;
}
return false;
}
};
After many hours i think i found a good solution. The call stays easy and there are no casts. It's a lot more complex than the C-Style version with memcopy but I think its nicer and has also the benefit that it works with complex data not just POD.
class Manager
{
public:
~Manager()
{
funcPtrs.clear();
}
void adFnc(void(*function)())
{
funcPtrs.push_back(function);
}
void runAll()
{
for(auto& val : funcPtrs)
val();
}
private:
std::vector<void (*)()> funcPtrs;
};
Manager gAllClearManager;
template<typename T>
class Data
{
public:
Data()
{
gAllClearManager.adFnc(clearValues);
}
static void clearValues()
{
values.clear();
}
static std::map<T*,std::vector<T>>& getValues() { return values; }
private:
static std::map<T*,std::vector<T>> values;
};
template <typename T>
static bool isChanged(T& entry)
{
const static Data<T>* dataP = new Data<T>();
static std::map<T*,std::vector<T>>& values = dataP->getValues();
auto it = values.find(&entry);
if(it == values.end())
{
values[&entry].push_back(entry);
}
else if(entry != it->second[0])
{
it->second[0] = entry;
return true;
}
return false;
}
template<typename T, size_t N>
bool isChanged(T (&entry)[N])
{
const static Data<T>* dataP = new Data<T>();
static std::map<T*,std::vector<T>>& values = dataP->getValues();
auto it = values.find(entry);
if( it == values.end())
{
for(int i = 0; i < N ; ++i )
values[entry].push_back(entry[i]);
return false;
}
else
{
for(int i = 0; i < N ; ++i )
{
if(it->second[i] != entry[i])
{
for(int j = 0; j < N ; ++j )
{
it->second[j] = entry[j];
}
return true;
}
}
}
return false;
}
template<typename T>
std::map<T*, std::vector<T>> Data<T>::values;
Now i can use it like:
int main() {
int ar;
std::string ba[6];
if(isChange(ar))
// Do something
if(isChange(ba))
// Do something
}
My first template is finally working! :) Thanks again Red Alert.

C++ GetName vector of objects

i have this class
class Dados
{
string name;
int valor;
public:
Dados(string n, int v) : name(n), valor(v){};
//~dados();
string GetName(){return name;}
int GetValor(){return valor;}
void SetValor(int x){valor = x;}
}
and this class, which basically reads a file and put the data into a vector:
class FileReader{
vector<Dados> dados;
public:
bool ReadFile(string file) {
dados.empty();
string fnome, ftemp;
int fvalor;
ifstream fich(file);
string linha;
if (fich.is_open())
{
while (fich.peek() != EOF){
getline(fich, linha);
istringstream iss(linha);
//cout << ".";
iss >> fnome;
iss >> ftemp;
iss >> fvalor;
dados.push_back(Dados(fnome,fvalor));
}
fich.close();
return 0;
}
else{
cout << "Ficheiro \""<< file <<"\" nao encontrado!";
return 1;
}
}
int FindOnVector(string fi)
{
int val;
vector<Dados>::const_iterator it;
it = dados.begin();
while (it != dados.end()){
val = it->GetValor();
it++;
}
return val;
}
};
But on class FileReader i need on method for find a name, and return int (valor).
This time he just doing this return value. Not this search a name.
but val = it->GetValor();
Give to me this error on VS 2012:
error C2662: 'Dados::GetValor' : cannot convert 'this' pointer from 'const Dados' to 'Dados &'
someon can me help?
Bests
Make the GetValor method const:
`int GetValor() const {return valor;}`
Declare the getter like this and it will work:
int GetValor() const {return valor;}
The const keyword indicates that calling GetValor does not modify the object.
Not related to your question, but this is wrong:
while (fich.peek() != EOF)
{
// ...
}
You should just have
while (std::getline(fich, linha))
{
// ...
}
To your original question, you need a getter for name that has a const modifier:
string GetName() const
{
return name;
}
The same goes for all your getters if you wish to use them in const functions/iterators.
First of all declare these functions as const
string GetName()const {return name;}
int GetValor() const {return valor;}
Secondly this statement in function ReadFile
dados.empty();
has no any sense. It simply returns true if the vector is empty. I think you meant
dados.clear();
As for searching an element of the vector then it is better to use standard algorithm std::find()or std::find_ifif you will use a lambda expression or a standard predicate . If you will use std::find you need to define operator == for class Dados.
As for your own function that you should decide what it will return in case when nothing was found. Suppose you will return 0. So the function could look the following way
int FindOnVector( const string &fi ) const
{
int val = 0;
for ( const Dados &d : dados )
{
if ( d.GetName() == fi )
{
val = d.GetValor();
break;
}
}
return val;
}

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) Error

This error occurs during run time, and I'm not sure what's causing it - the code looks correct to me.
#include <iostream>
#include <string>
using namespace std;
struct Room {
int d_noSeat;
bool d_hasProjector;
Room() = default;
Room(const Room& r);
};
class Event {
Room* d_room;
std::string d_name;
public:
Event();
Event(const Event& e);
~Event();
void set(Room r, const std::string& name);
void print();
};
Event::Event() : d_room(0), d_name("") {};
void Event::print() {
std::cout << "Event: " << d_name;
if (d_room != 0) {
std::cout << " in size " << d_room->d_noSeat;
if (d_room->d_hasProjector)
std::cout << " with";
else
std::cout << " without";
std::cout << " projector";
}
std::cout << std::endl;
return;
}
void printEvent(Event e) {
e.print();
return;
}
void Event::set(Room r, const std::string& name) {
d_room = &r;
d_name = name;
}
// Room shallow copy constructor
Room::Room(const Room& r) :
d_noSeat(r.d_noSeat),
d_hasProjector(r.d_hasProjector)
{ }
// Event deep copy constructor
Event::Event(const Event& e) :
d_name(e.d_name),
d_room(new Room(*e.d_room))
{ }
// Event destructor
Event::~Event()
{
delete[] d_room;
}
int main() {
const int noLect = 5;
Room r;
Event lectures[noLect];
for (int i = 0; i < noLect; ++i) {
r.d_noSeat = i + 1;
r.d_hasProjector != r.d_hasProjector;
lectures[i].set(r, "CSI2372");
lectures[i].print();
}
std::cout << "-------------------" << std::endl;
for (int i = 0; i < noLect; ++i) {
printEvent(lectures[i]);
}
return 0;
}
The error apparently occurs at line 52 (first line in the print() function). In addition to this, the printed text displays numbers that are very large and often negative. What is causing this?
Issue
void Event::set(Room r, const std::string& name)
{
d_room = &r;
// ^
d_name = name;
}
You are referencing to the temporary object: Room r passed by value, which is destroyed at the end of the scope: }.
Instead you must reallocate the member pointer:
d_room = new Room(r);
Why it went wrong
Because you are writing C-style code in C++ classes.
In C++ we tend to:
Avoid naked pointers, prefer smart pointers:
class Event
{
std::shared_ptr<Room> d_room;
...
Event::~Event() { /* no need to delete */ }
Use constructor overloading (instead of using set-like functions after construction):
Event(Room& r, const std::string& name):
d_room(new Room(r)),
d_name(name)
{}
Pass by reference:
void set(Room& r, const std::string& name);
Avoid raw arrays, use STL facilities instead:
std::vector<Event> lectures;
// or
std::array<Event, 5> lectures;
Another issue
r.d_hasProjector != r.d_hasProjector; // checks if r.d_hasProject is not itself
You probably want
r.d_hasProjector = !r.d_hasProjector;
Complete code: link
Also, here is a must-read link about advanced C++ stuff which, I believe, will be very useful to you: http://www.parashift.com/c++-faq/
Edit: I forgot about your question:
In addition to this, the printed text displays numbers that are very large and often negative. What is causing this?
Those numbers are garbage. Variables that are not explicitly initialized are not initialized at all. Memory is allocated but holds old information from previous program. It could contain anything. When you read from uninitialized variables, you'll get this garbage. You had a pointer which was pointing to a destroyed object. So the pointer was effectively uninitialized.
Your problem is here:
void Event::set(Room r, const std::string& name) {
d_room = &r;
d_name = name;
}
The &r takes the address of an object whose lifetime ends when the function returns, resulting in undefined behaviour when you later try to access it.
If you want to use pointers, you need to allocate them dynamically:
void Event::set(Room* r, const std::string& name) {
d_room = r;
d_name = name;
}
// ...
for (int i = 0; i < noLect; ++i) {
Room* r = new Room;
r->d_noSeat = i + 1;
r->d_hasProjector != r.d_hasProjector;
lectures[i].set(r, "CSI2372");
lectures[i].print();
}
// ...
But it doesn't look like you need pointers here, you should be able to have
Room d_room;
in the Event class.