« first day (1926 days earlier)      last day (933 days later) » 

12:32 AM
int main() {
  std::vector<int> x = {3, 2, 5};
  int& y = x.at(1);
  x.erase(x.begin() + 1);
  std::cout << y;
}
is this undefined behavior?
 
12:47 AM
@JBis Yes but only because the reference isn't constant IIRC
either way it's dumb
 
@Mgetz wdym?
the output of that on gcc is 5, which makes sense
the reference acts as a pointer
 
can't find it anymore and maybe it's not a thing, but a dangling reference that was const used to get extended
either way it's a dangling reference and thus UB
 
@Mgetz would a pointer be UB as well?
i would think not
 
1:02 AM
dangling reference is dangling reference
 
int main() {
  std::vector<int> x = {3, 2, 5};
  int* y = &x.at(1);
  x.erase(x.begin() + 1);
  std::cout << *y;
}
 
as soon as you call erase all pointers, references, and iterators on that vector are invalid
so touching them is undefined behavior
 
@Mgetz hmm
 
please don't ping reply unless you're replying to something further back and a specific line
otherwise it's just annoying
 
The underlying structure is an array. And erase just move stuff around and changed the end location. So unless the reference/pointer is the end value I would think it would be defined behavior.
 
1:05 AM
no
because it can reallocate
 
arrays are guaranteed to be stored linearly in memory
i don't see how it could be reallocated
 
runtime decides to dump memory
it reallocates to a smaller array
it's a vector
it's dynamically allocated
if you modify a vector it's perfectly legal for the runtime to do that
 
couldn't the same be said without the erase function?
 
see part about modifying
it's ONLY valid on modification
 
int main() {
  std::vector<int> x = {3, 2, 5};
  int& y = x.at(1);
  x.push_back(8);
  std::cout << y;
}
push_back is a modification
 
1:08 AM
yes and that invalidates pointers iterators and references
doesn't matter HOW
it just matters that it happens
 
oh really? interesting...
 
if you want pointer stable use deque
 
en.cppreference.com/w/cpp/container/vector where is that documented if i may ask, for future reference
 
there are specific side cases but eel.is/c++draft/vector#modifiers
either way... don't trust implementations to be 100% compliant
because not a single one is
 
thank you for your help!
it can be difficult to tell what is and isn't UB sometimes
 
1:12 AM
dangling references are always UB
a pointer to a dangling reference is UB
a pointer to an element in the vector is not necessarily UB
but may be invalid in the wrong circumstances
part of the issue you were running into was .get()
which returns a reference
which normally isn't an issue because people operate on it directly so it never dangles
 
1:32 AM
wait whats a UB?
 
 
5 hours later…
7:19 AM
Can compiler reorder non-critical-section operations into a critical section across mutex lock/unlock statements?
What barriers are enforced by mutex lock/unlock?
mem_op1
lock()
mem_op2
unlock()
mem_op3
can mem_op1 and mem_op3 be moved inside? cppreference doesn't say what barriers are used at lock and unlock.
 
8:05 AM
Shouldn't there be something more than ld.acq to lock a mutex? Shouldn't there be some write?
How would other threads otherwise know that the mutex has been locked?
 
8:22 AM
other threads are only guaranteed to observe the changes if they lock the same mutex, so they would have to ld.acq themselves to observe all the changes until the st.rel, right?
 
@PeterT What if another thread does ld.acq and enters CS before the other thread does st.rel?
I am confused. What is being stored into the mut variable?
I am trying imagine the mutex to be some sort of a flag indicating whether the lock is taken or not. So when it's taken, there should be a write marking it as taken before entering the CS. It's that write I am looking for.
 
oh, yeah. I don't think that's the "only instruction needed for the lock". It's the instruction guaranteeing the ordering part, but not the one guaranteeing the exclusive part
 
 
2 hours later…
10:52 AM
why does size template not work on an array of structs?
I made this template to find size of array quickly: template<typename T,size_t N>
T size(const T (&array)[N])
{
return N;
}
however this does not work on an array that has struct objects
 
@Electrical_engineer_student the return type is wrong
it's supposed to be size_t, not T
 
ah, ok that makes because 'T' would mean the templates expects to return an array?
 
nah it would return the array element type, that's why it worked with stuff like "int[]"
 
ok thanks, it makes sense now.
how can you print out an uint8_t ? So I have a array of pointers but want to print out the index(uint8_t) from the class. so I did this: for (size_t i{};i<3;++i)
{
std::cout<<pUSBarray[i]->index<<".\n";
}
but this displays '.' which is not expected ?
 
casting it to int is the easiest thing for now
because it's often typedef'd to char, so it's char overloads from std::cout << that you get
 
11:07 AM
@PeterT is this code OKAY?
for (size_t i{};i<3;++i)
{
std::cout<<static_cast<int>(pUSBarray[i]->index)<<".\n";
}
 
seems fine to me
 
@PeterT thanks man, that helped
 
 
1 hour later…
12:37 PM
@mqmarathon hello, you can ping (@sehe) me here, and we can even split of another chat room if you want.
 
 
3 hours later…
nwp
3:07 PM
You probably shouldn't post your email address here. It's publicly accessible forever.
 
Where can I find complete material on memory models, atomics, barriers, etc?
 
@nwp Thanks for letting me know. This is not the prettiest chat interface I have seen lol. Not sure how to edit. But if it's not possible, that's still fine with this email.
 
nwp
You can only edit within 2 minutes of posting. If it's important you can flag it for moderator attention, but try not to do that too often.
 
3:29 PM
@mqmarathon seen your message, flagged for privacy issue - probably deleted soonish
 
Where is std::mo_relaxed defined? I cannot find cppreference documentation for these short forms.
but plenty of blog posts use it
 
4:01 PM
An OOO processor can issue loads out of program order. The x86 memory model says reads are not reordered with reads. How do I understand this statement? Does that mean all later loads are dependent on current loads even if they access different locations?
I think I have misunderstood something. Not being able to reorder reads after reads implies that all loads are serialized which implies you can have at most one load-store unit and the scheduler should send loads in program order. I don't feel like this is how processors work.
 
nwp
Maybe they can happen at the same time.
 
Suppose there are two load-store units and you simultaneously issued two adjacent load instructions to the two units. What if the earlier load happens to be an LSQ miss and the later load happens to be a LSQ hit?
Will the load that had an LSQ miss block the load that had an LSQ hit just to ensure ordering of loads?
 
nwp
That's what the reordering rule implies. No clue if that's what actually happens.
 
It also feels like this ordering requirement may hurt latency hiding capabilities. If there is an LLC miss, then all later independent loads would have to be stalled even if they could potentially be resolved via LSQ or L1 or from somewhere.
 
 
1 hour later…
5:21 PM
Hi, I tried to use std::chrono to measure the speed of my code.
code snippet:
auto start1 = std::chrono::steady_clock::now();
// add the new element to pUSBarray, between the second and third elements
pUSBaddarray(pUSBarray, &USB3, 2);
auto end1 = std::chrono::steady_clock::now();
std::cout << "Time taken for the pointer array: " << (end1 - start1).count()<<" .\n";
the problem is that this outputs and large number like 100. Not sure what is going on because on the cpp reference page it should output seconds not something big like that?
 
@Electrical_engineer_student if you cast it to seconds yes...
also if you want to test something for a benchmark... you need to do a lot more than a single call
like a couple hundred thousand
along with at least one run prior to warm things up
 
this was testing to compare how long it takes a function that calls by value vs call by address(of course the pointer function is faster every time).
@Mgetz do std::chrono a hundred thousand times? Like use a for loop and store each time in a vector and find its mean.......... surely not
 
no
your call you're trying to test
then you divide the time it took by the number of iterations
there are a LOT of things that can cause run to run variance in the 1000% range
so by running a large number you get around that for average time
 
thanks man will do
 
6:15 PM
class Test {
  int* x[2];
  Test(int* x[2]){
    this->x = x;
  }
};
why isn't this->x assignable?
 
<source>: In constructor 'Test::Test(int**)':
<source>:4:13: error: incompatible types in assignment of 'int**' to 'int* [2]'
also please never ever actually do that
 
ah
my compiler gave a worse error
sorry for ping
 
Please don't ping reply unless it's something way back
 
I am unsure how to handle this issue then. I guess that was an XY.
 
regardless... I'd advise away from using pointer to pointers unless you're interoperating with C APIs
 
6:23 PM
I have an abstract class Player, and I need to store an array of Players
stackoverflow.com/questions/33123371/… this suggested array of pointers
 
are they actually polymorphic?
 
Yes
There are two types of players, the array needs to be able to store any type of Player
 
9
A: how to create array of an abstract class in c++

Bartek BanachewiczYou need reference semantics for that, because Food arr[2]; tries to initialize the array with default values (which are abstract, thus not constructible). I think std::array<std::unique_ptr<Food>, 2> arr; should be the most natural to use in this case. std::array<std::unique_ptr<Food>> arr = {...

either way you don't need raw pointers here
and I'd avoid them
 
Unfortunately I must use raw pointers or at least cannot use smart pointers
 
why not?
you're literally ignoring the most important feature of C++
 
6:28 PM
It is a restriction on the assignment
I agree it is stupid
 
ah you have an idiot for a professor
and yes you can assume I added and expletive I didn't write there
 
I was given a code, I understand it has a lot of weak points, e, g. the arguments could be not integers. Anyway, I know that the order of arguments to be pushed onto the stack is not defined in standard(the last argument can be pushed before the first one and vice-versa), so some compiler could push onto the stack first the variadic arguments and then the argument k and the program would try to reach some other data on the stack or just get a segmentation fault, am i right?
`int sum(int k, …)
{
int *p = &k;
int s=0;
for ( ; k!=0; k--)
s+=*(++p);
return s;
}`
 
I'm not sure how to handle this
A pointer to an array would be fine
 
So what you're doing is... seriously undefined behavior. But mostly because k may not be passed on the stack at all
but also because anything variadic must be access through the varargs macros
 
@Mgetz I know it's terrible, but I was given it from my university :)
Just wanted to know if I'm right
 
6:36 PM
so your professor is even dumber than JBis'
so k can't be pushed last, but it might not be passed on the stack at all
many RISC architectures pass fixed arguments in registers (x86 does too)
 
Why k can't be pushed last?
 
Because it's the fixed argument, the callee must know where to look for it
it's literally the only concrete thing you're passing in
if you look at the link I posted it's practically the same code you posted, only actually written safely.
 
I understand now. Thanks, have a nice day
 
 int x[] = {3, 2};
  auto y = &x;
whats the syntax for the explicit type of y?
 
6:51 PM
int**
but please don't do that
 
I'm not sure how to do it then
I was going to have the constructor accept a pointer to an array
Or I guess I could just accept a Player* (pointer to the first element in the array)
 
then how many players do you have?
 
Yes that's an issue
 
are you allowed to use std::vector at least?
 
I mean technically it's static, but i shouldn't rely on that
yes, but would rather not if i don't need to
(sorry, habbit)
 
6:54 PM
it's always the better choice than c style arrays
in almost every case
or heck... std::span if you can use C++20
I can't help you fix professorial stupid... but at least std::vector actually behaves like you seem to think c style arrays do ;p
 
I can use std::array too
Oh wait I can't because Player is abstract :(
I (think I) understand why that restriction exists, but that's so annoying
    std::vector<Player> players;
   Game(..., const std::vector<Player>& players) {
    ...
    this->players = players;
  }
now whats wrong with that
In template: no matching member function for call to 'assign'
 
wut
I mean there are inefficiencies there, but your bigger issue is that vector can't be polymorphic` unless you're holding pointers or smart pointers
 
so i need a vector of player pointers?
this is such a mess
  std::vector<Player*> players
^ that works
for future reference whats inefficient with that?
 
7:13 PM
so if you pass in a vector you're planning to store as const& then you prohibit the caller from std::moving in a vector and saving allocations and copies
also when assigning member variables... do them in the initializer list and not the body of the constructor if possible to avoid double initialization
but to expand on the move thing... you can avoid copying the vector entirely if the caller is aware
foo(std::vector<bar> foobar): m_foobar(std::move(foobar)){} is a lot more efficient than what you're doing
also this is more efficient only because a constructor is a sink and is grabbing ownership
 
7:45 PM
thank you
 
8:30 PM
why can i do this but not this?
 Game(..., std::ostream& out): out(out) {  // works
Game(..., std::ostream& out) {  // doesnt
  this->out = out;
}
class Game {
    std::ostream& out;
also how am i able to define a reference type as a member? wouldn't it be an uninitialized reference?
i might have answered my own question...
 
8:56 PM
because the initializer list ensures it's initialized
 
 
2 hours later…
10:40 PM
What is the point of having a double ampersant here?
template <typename T>
void setCallback(T&& f)
{
    callback = std::forward<T>f;
}
The way I understood it is that having a double ampersant, aka rvalue reference, is so that you don't have to have the const specifier in function signatures:
void fnc(const int& x)
{
}

int main()
{
    fnc(10);
}
can now become:
void fnc(const int&& x)
{
}

int main()
{
    fnc(10);
}
Hmm maybe this has something to do with "perfect forwarding"...
urgh cant edit anymore, but the second example where you pass the 10 as argument, should -obviously- not have the const specifier. Should just be void fnc(int&& x)
 
11:33 PM
@Electrical_engineer_student besides the "use a proper micro benchmark" (quick-bench or nonius?) always use chrono in the human way: coliru.stacked-crooked.com/a/4291f8c4513cc78d
@LandonZeKepitelOfGreytBritn the real question is "why would not needing the const be helpful?" - it's not about somehow reducing stress on those 4 keys on the keyboard
Do you know what an rvalue reference means? Or rvalue, for that matter? Because that's the key. When you ask "what does T&&" mean, going by "what other thing now changes" is indirect, There are absolute, direct answers (multiple, because T&& means different things depending on context)
 
@sehe the way I understood it: an rvalue is a-n intermediate- value which is actually not stored anywhere explicitely, eg: int y = 5. If you however were to have int y = x, you actually have 2 lvalues. Now the rvalue reference is actually a feature which allows you to have the address of that (unstored) intermediate value. By doing: int x = 5; int& y = x; you created an alias for x of type int& and y is now an alias for x thanks to the underlying dereferencing
 
That's a decent summary of rvalue.
 
in Assembly you d have mov #5,addressOfY, as you can see here 5 is not stored anywhere it is an explicit number in that case
 
What benefit is there to have a reference to a temporary?
 
@sehe the added value of a reference is that you can pass it as an argument to functions and that it cannot be NULL, which in turn alleviates the need for defensive coding patterns where you check for nullptr and also does not lead you to undefined-behaviour-land
that s the benefit of a reference, not the benefit of a reference to a temp though...
 
11:45 PM
@LandonZeKepitelOfGreytBritn I think you are putting too much stock in "references are addresses". That's not actually relevant.
The key is "move semantics". By having a reference that is "qualified" as an rvalue-reference the compiler is allowed to move from them (as, logically rvalues weren't going to be used after the fact. say:
struct MyStruct {
    std::string hold_me;

    MyStruct(std::string&& take_me)
        : hold_me(std::move(take_me))
    {}
};
@LandonZeKepitelOfGreytBritn (exactly)
Rvalue reference would be worth NOTHING without move semantics. Move semantics are to avoid this very very typical pre-c++11 pattern: godbolt.org/z/9aGshE5aY
Here first a temporart string is constructed for the argument, which is then **copied** to the member variable. Then the temporary is destructed.
Actually this used to be a painful downside from being the language with value-semantics all around: for really performant code you sort-of **had** to use dynamic allocation a lot to avoid ineficient cases like with these absolutely common vocabulary types.
Since C++11 you can take the string by value and std::move() from it, replacing a copy with a move, which can often be equivalent to just copying a member pointer(s). Effectively, you can /write/ value semantics and the compiler can /emit/ the optimized code.
Now, there are two kinds of caveats:
1. taking std::string&& signals to the caller that the receiver intends to (potentially) move from the argument, but to do so, it must still tell the compiler again with std::move (godbolt.org/z/n9fWrdTsE)
 
@sehe Still reading on the matter as we speak, but long story short: rvalue referencing leads to move semantics, while const T& leads to copy semantics. Right?
 

« first day (1926 days earlier)      last day (933 days later) »