How to reconstruct non-pointer class member containing vector? - c++

I'm facing a weird issue : I can't reset (destruct and construct) properly an attribute containing a vector. It causes a segmentation fault when trying to access the vector.
Here is my code (witten in C++11). I think I simplified it the most possible to underscore the issue, but I might be wrong, sorry about that.
The goal would be to print two times two different (random) vectors. The first vector is working well, the second is completely failing for an unknown reason.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
class A
{
std::vector<int> n;
public :
A();
std::string toString() const;
};
A::A()
{
for (int i = 0; i < 10; i++)
n.push_back(std::rand()%10);
}
std::string A::toString() const
{
for (auto i : n)
std::cout << i << ' ';
std::cout << std::endl;
}
class B
{
A a;
public :
void resetA();
A getA() const;
};
void B::resetA()
{
a = A();
}
A B::getA() const
{
return a;
}
int main()
{
srand(time(NULL));
B b;
std::cout << b.getA().toString();
b.resetA();
std::cout << b.getA().toString();
return EXIT_SUCCESS;
}
For some reason, I would like to avoid pointers and dynamic allocation as far as possible. It would fit less with my UML conception.
Moreover, this code is working well when using simple int (no vectors).
Thank you.

Your toString() doesn't return anything, so your program has Undefined Behaviour (and, in practice, returns random garbage which is most certainly not a valid std::string object).
Perhaps you wanted to use a string stream instead?
#include <sstream>
// ...
std::string A::toString() const
{
std::ostringstream s;
for (auto i : n)
s << i << ' ';
s << '\n';
return s.str();
}
Live example.
Generally, it's a good idea to compile with as many warnings turned on as possible. This would certainly have been reported as a warning then. For this particular warning (no-void function not returning anything), I strongly suggest treating it as an error.

Related

How to make a C++ map with class as value with a constructor

I have a class that has a constructor. I now need to make a map with it as a value how do I do this? Right now without a constructor I do.
#include <iostream>
#include <map>
using namespace std;
class testclass {
public:
int x = 1;
};
int main()
{
map<int,testclass> thismap;
testclass &x = thismap[2];
}
If I added a constructor with arguments how would I add them to the map? I basically need to do
#include <iostream>
#include <map>
using namespace std;
class testclass {
public:
int x = 1;
testclass(int arg) {
x = arg;
}
};
int main()
{
map<int,testclass> thismap;
testclass &x = thismap[2];
}
This obviously wouldn't work since it requires an argument but I can't figure a way of doing this.
This is how you can add items of your own class to your map.
Note : I used a string in testclass to better show difference
between key and value/class.
#include <iostream>
#include <string>
#include <map>
class testclass
{
public:
explicit testclass(const std::string& name) :
m_name{ name }
{
};
const std::string& name() const
{
return m_name;
}
private:
std::string m_name;
};
int main()
{
std::map<int, testclass> mymap;
// emplace will call constructor of testclass with "one", and "two"
// and efficiently place the newly constructed object in the map
mymap.emplace(1, "one");
mymap.emplace(2, "two");
std::cout << mymap.at(1).name() << std::endl;
std::cout << mymap.at(2).name() << std::endl;
}
Using std::map::operator[] requires that the mapped type is default-constructible, since it must be able to construct an element if one doesn't already exist.
If your mapped type is not default-constructible, you can add elements with std::map::emplace, but you still can't use std::map::operator[] to search, you will need to use std::map::find() or so.
That's a rather obvious feature of std::map (and very similar other std containers). Some of their operations require specific type requirements for good reasons.
There is no problem to create such a map as you suggest in the first place, however, you are restricted to method calls that do not require potential default construction. The operator[] is such a method, since in the case the element is not found, it is created. That is what does not work in your example. Just use other methods with little impact on the map usage and you can still succeed:
#include <iostream>
#include <map>
using namespace std;
class testclass {
public:
int x = 1;
testclass(int arg) {
x = arg;
}
};
int main()
{
map<int,testclass> thismap;
thismap.insert( {2, testclass(5)} );
auto element2 = thismap.find(2);
if (element2 != thismap.end()) {
testclass& thiselement = element2->second;
cout << "element 2 found in map, value=" << thiselement.x << endl;
}
auto element5 = thismap.find(5);
if (element5 == thismap.end()) {
cout << "no element with key 5 in thismap. Error handling." << endl;
}
}
Main issue: avoid operator[].
Note:
Looking at the other very good answers, there are a lot of methods that can be used without default construction. There is not "right" or "wrong" since this simply depends on your application. at and emplace are prime examples that are highly advisable.

"Potential memory leak" with std::function

Consider this example:
#include <vector>
#include <string>
#include <functional>
#include <iostream>
using closure_type = std::function<void(void)>;
using closure_vec = std::vector<closure_type>;
class callbacks {
static closure_type common(std::string name, uint32_t number) {
return [number, name]() { std::cout << name << number << std::endl; };
}
public:
static closure_type foo(uint32_t number) { return common("foo ", number); }
static closure_type print(std::string msg) {
return [msg]() { std::cout << "print " << msg << std::endl; };
}
};
template <typename... calls_t> closure_vec wrap(uint32_t number, calls_t &&... calls) {
return closure_vec {
callbacks::foo(number),
std::forward<calls_t>(calls)...,
};
}
int main() {
auto vec = wrap(42,
callbacks::print("hello, "),
callbacks::print("world"));
for(auto &e: vec)
e();
return 0;
}
Demo (On the right most tab there is a full message)
When this code is checked with clang-tidy, I get the following warning:
warning: Potential memory leak [clang-analyzer-cplusplus.NewDeleteLeaks]
The line number points at the scope exit of the wrap function.
As I understand the message, the tool is concerned that the results form callbacks::foo might be lost. But I don not understand how is it possible: std::function is a safe class and should destroy everything nicely in its destructor. Also its lifetime is controlled by the vector which is safe too.
What is going on here? How do I fix this or workaround?
Unfortunately I cannot just suppress the warning, as this code is scattered everywhere in the codebase.
Try
closure_vec retval;
retval.reserve(sizeof...(calls)+1);
retval.push_back(callbacks::foo(number));
( retval.push_back(std::forward<calls_t>(calls)), ... );
return retval;
this avoids the const initializer_list contained copies of std function your code created, so should be more efficient as well.
Live example.
I tried using a C style array here, but I got the warning as well despite not using a std::initializer_list.
This also works:
std::array<closure_type, sizeof...(calls)+1> tmp ={
nullptr,
std::forward<calls_t>(calls)...
};
tmp[0] = callbacks::foo(number);
return {std::make_move_iterator(std::begin(tmp)), std::make_move_iterator(std::end(tmp))};
the problem is callbacks::foo(number) within the initalization.

Is it possible to call a method from an instance that doesn't exist?

The code I'm working on :
I had the following code (with an error about the index in main.cpp) :
Sample.hpp :
#ifndef SAMPLE_HPP
# define SAMPLE_HPP
# include <iostream>
# include <string>
class Sample{
public:
Sample(void);
~Sample(void);
void tellname(void) const;
private:
std::string _name;
};
#endif
Sample.cpp :
#include <iostream>
#include "Sample.hpp"
Sample::Sample(void){
this->_name = "testname";
return;
};
Sample::~Sample(void){
return;
}
void Sample::tellname(void) const{
std::cout << "Name : " << this->_name << std::endl;
return;
}
main.cpp
#include "Sample.hpp"
int main(void){
int i;
Sample *test;
test = new Sample[4];
i = 0;
while (i++ < 4) // I know : i++; shouldn't be here
test[i].tellname();
delete [] test;
return 0;
}
If I compile this I get the following output :
Name : testname
Name : testname
Name : testname
Name :
My question is :
About the last line, it calls a method (void Sample::tellname(void)) but from an instance that is not in the range of the table (test[4] doesn't exist).
However, it still calls tellname() even the instance it calls it from doesn't exist. It just considers its _name field being empty.
How is this possible?
It's simply undefined behavior, something C++ imposes no requirements on so "anything could happen". What you're seeing is just a coincidence and worthless to reason about: next time you run it could crash, display nyan cat and so on.
It sounds like you are wondering why the function is called. In memory, structs do not contain the functions inside them. Instead, one copy of the functions are placed somewhere in the executable. So when you are calling test[4].tellname() what is really happening is: The address test + (4 * sizeof(Sample)) is passed to the function tellname(). The value at that address is undefined.
Here is an example to give you an idea of what is going on:
#include <iostream>
struct astruct {
int i = 0;
void prnt()
{
std::cout << i << '\n';
}
};
struct bstruct {
int y = 100;
};
int main()
{
bstruct b;
((astruct*)&b)->prnt();
getchar();
return 0;
}
Here prnt() is behind the scenes being passed the address of bstruct and treats it like the address of an astruct, since the first value in bstruct is 100, it prints 100. You can even simplify it to this:
#include <iostream>
struct astruct {
int i = 0;
void prnt()
{
std::cout << i << '\n';
}
};
int y = 100;
int main()
{
((astruct*)&y)->prnt();
getchar();
return 0;
}
i goes from 1 to 4 include, since tellname is const, test[4].tellname() is Sample::tellname with Sample being an undefined structure so "Name :" is rightfully printed then the memory in test[4]._name is printed and luckily the memory pointed by test[4]._name* is non null and is even a end string char.
So yeah you are lucky.

A strange behavior about constructors in C++

I show you the code directly.
#include <iostream>
#include <stdio.h>
class A {
public:
A(const std::string& name){
std::string aname = "HAHA_" + name;
std::cout << aname << std::endl;
}
~A(){
std::cout << "Done." << std::endl;
}
};
int main() {
size_t len = 5;
char szTmp[30] ={0};
snprintf(szTmp,sizeof(szTmp),"Getlist_V2_%zd",len);
A a(std::string(szTmp));
return 0;
}
The expected results are as follows:
HAHA_Getlist_V2_5
Done.
But It outputs nothing at all. When I replace A a(std::string(szTmp)); with
A a(szTmp); ,erverything is ok. It confused me for a long time.
A a(std::string(szTmp));
This is a function declaration, believe it or not! So, no A is constructed.
Instead, write this:
A a{std::string(szTmp)};
Or, since an implicit conversion to std::string exists, either of the following will suffice:
A a{szTmp};
A a(szTmp);

Async with reference lambda crashing

I'm curious as to why this would crash in around 1 runs in 4.
I have a simple class that returns a string with a thread id.
This class is called from within another class asynchronously in a lambda and returns the result. The code is as simple as I can make it - I'm still learning:
class String_Returner
{
public:
string run() const
{
return "I returned from thread "+to_string(this_thread::get_id());
}
};
class Class_Holder
{
public:
Class_Holder() : number_of_runs(10)
{
srs.resize(number_of_runs);
}
void concurrent_srs()
{
for (int i = 0; i < number_of_runs; i++)
{
results.push_back(async([&]{return srs[i].run();}));
}
for (int i = 0; i < results.size(); i++)
{
cout << i << ") " << results[i].get() << endl;
}
results.clear();
}
private:
vector<future<string>> results;
vector<String_Returner> srs;
const int number_of_runs;
};
void class_b_test()
{
Class_Holder ch;
ch.concurrent_srs();
}
I realize using async with a reference is dangerous, but I figured it'd be safe if nothing is being written. I think my error probably comes from the lambda itself. This is mainly a programme to test the functionality of async and lambdas.
So my main questions:
1) Why is it crashing?
2) What better ways are there to do this?
Why is it crashing?
results.push_back(async([&]{return srs[i].run();}));
There's nothing wrong with the reference to srs in that line; as you say, it is not being modified. But the reference to i is completely meaningless; i may no longer exist when the lambda executes, and its value will be unpredictable.
But I don't understand why you feel the need to have more than one StringReturner. The class has no state, and the run method might as well be static for all the difference it makes.
What better ways are there to do this?
Do what, exactly?
If you're going to use a lambda anyway, why not just use one that directly does what you want:
#include <string>
#include <iostream>
#include <thread>
#include <future>
#include <sstream>
#include <vector>
int main() {
std::vector<std::future<std::string>> rets;
auto f = []() {
std::ostringstream b;
b << "returned from: " << std::this_thread::get_id();
return b.str();
};
for (int i=0; i<10; i++)
rets.emplace_back(std::async(f));
for (auto & t : rets) {
t.wait();
std::cout << t.get() << "\n";
}
}
Note that the thread::id type that get_id returns is guaranteed to have an operator<<, but at least as far as I know, there's no guarantee that it's a type for which std::to_string has been overloaded.