website-copy icon indicating copy to clipboard operation
website-copy copied to clipboard

"We received the following error when we ran your code:" but no error is following

Open bakaiadam opened this issue 3 years ago • 2 comments

I'm on the site: https://exercism.org/tracks/cpp/exercises/circular-buffer/edit

My .hh source code is:

#if !defined(CIRCULAR_BUFFER_H)
#define CIRCULAR_BUFFER_H
#include <vector>
#include  <stdexcept>
using namespace std;
namespace circular_buffer {
template<typename T>
class  circular_buffer
{

public:
int pos=0;
int writepos=0;
int len=0;
vector<T> elems;
int num;
circular_buffer(int num): elems(num)
{
    num=num;
}





T read()
{
    if (len==0)
        throw domain_error("alma");
    len--;
    T ret= elems[pos];
    pos=(pos+1)%num;
    return ret;
    
}

void write(T a)
{
    if (len==num)
        throw domain_error("alma");
    len++;
 
    
    writepos=(writepos+1)%num;
    elems[writepos]=a;
    
    
}

void clear()
{
    len=0;
    
}

void overwrite(T a)
{
       if (len==num)
       {}
    else
    len++;
 
    
    writepos=(writepos+1)%num;
    elems[writepos]=a;

    
}


};

}  // namespace circular_buffer

#endif // CIRCULAR_BUFFER_H

The .cc source code is the default

bakaiadam avatar Jun 14 '22 21:06 bakaiadam

I don't know why the website reported an error but didn't show it.

But maybe I can help with the code. Look at the constructor. In the function body it assigns num = num;. That doesn't work, officially it reads an uninitialized member variable num (invoking undefined behavior), but in practice that statement will probably do nothing, and num still has an "indeterminate value". Instead initialize num in the "member initializer list", just like elems: : elems(num), num{num} { } In that context the first num in num{num} refers to the member variable, the second one to the parameter.

siebenschlaefer avatar Jun 14 '22 22:06 siebenschlaefer

thank you. with your help, i managed to solve the exercise.

bakaiadam avatar Jun 15 '22 06:06 bakaiadam