« first day (225 days earlier)      last day (2631 days later) » 

12:08 PM
Can anyone tell me why my program crashes?
It's a simple code:
std::string input;
std::cin >> input;

int a = input.at(0);
int b = input.at(2);
For input I do "2 5"
But if I do std::string input = "2 5" it works just fine
 
nwp
@sweg_yolo_69 read the docs
 
std::cin >> input; reads until the first whitespace
 
nwp
and use the right room
 
12:25 PM
@nwp That room seems a bit dead
What I'm trying to do, is I have input in the form of "2 5"
I want to extract 2 and 5 as separate ints
And so far, it seems really hard
With all the type conversions and everything
 
int a, b;
std::cin >> a >> b;
it should work that way
 
in C++ Questions and Answers, Aug 30 '16 at 7:36, by milleniumbug
You don't ask a question because room is empty? Well, it's empty because you haven't asked the question!
 
@BogdanMarginean Yep that was it
I literraly spent like 40 minutes trying to figure out how to get a substring, convert it to int then do calculations
 
reading the docs of cin would've been faster
 
@BogdanMarginean True, although the text of the exercise I was doing made it seem like the input was a string
And the chapter was about strings
 
Ell
1:15 PM
@sweg_yolo_69 grrr
 
1:25 PM
Hello
I'm reading through "Effective C++"
Especially the item 7: Declare destructors virtual in polymorphic base classes
and I was wondering about this statement at some point "If a class does not contain virtual functions, that often indicates it is not meant to be used as a base class"
And I'm not sure of what this mean
 
composition over inheritance
 
I'm sorry?
Isn't purpose of virtual function indeed to enable certain mechanism in inheritance?
 
though here it's more the case that the base class without virtual functions cannot be used as a derived class without casting
and casting is bad, mmkay
 
I still don't understand
why "not having" virtual functions indicates that a class is probably not meant to be used as a base class?
 
there is no use to having a base class that has no virtual functions because if other code has a ref to the derived class it can only interact with the derived class after casting.
whereas if there were virtual functions those virtual functions would be the pathway to the derived class
 
Ven
1:31 PM
@user8469759 because you can't safely inherit from it
it means there's no behavior to override, so it's useless as a base class
 
so the statement should be necessarily be interpreted in a context where I want necessarily to inherit
because I can think the trivial case I have a single class with no derived classes
which is a specific case a base class, where the hierarchy depth is 0
Later in the chapter it is also mentioned that
classes that are not meant to be base classes
shouldn't declare any virtual destructor
where is the problem there?
 
virtual is slow
 
"slow" or "memory consuming?"
 
it's a bit of a simplification though
 
It makes the point of the implementation of the virtual table whether you declare a function virtual
With reference to the following class
 
1:40 PM
the more precise statement is that a virtual call can act as a barrier to inlining and subsequent optimizations
 
class Point {
 public:
   Point(const int& x, const int& y);
   virtual ~Point();
 private:
   int x, y;
}
it is said
What is important is that if the Point class contains a virtual
function, objects of that type will increase in size
it doesn't mention the speed
 
sizeof(Point) will be twice as large than without the virtual. (assuming 64 bit system)
it also stops being a POD type
 
what's a POD type?
 
plain old data
and it violates rule of 3 (or 5)
 
I'm not sure what you mean here
 
1:44 PM
rule of 3 states that if you define a destructor you must also define (or disallow) copy constructor and copy assign operator.
otherwise the compiler will auto generate one that will most likely lead to double frees or dangling pointers
 
So the class I posted
is 1
wrongly implemented because of the useless virtual destructor
(since it is intended not to be polymorphic)
2 even if it were it wouldn't be correct because of the rule of 3?
 
are there other rules like this to keep in mind?
and If yes is there a comprensive reference?
(sorry I meant comprehensive)
 
2:24 PM
21 messages moved from Lounge<C++>
 
May I ask one more question? It's about C++ best practices again
There's this example
class WebBrowser {
public:
...
void clearCache();
void clearHistory();
void removeCookies();
...
};
With the assumption that later the following method is added
class WebBrowser {
public:
...
void clearEverything(); // calls clearCache, clearHistory,
// and removeCookies
...
};
Alternatively "clearEverythin()" can be implemented as
void clearBrowser(WebBrowser& wb)
{
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
}
i.e. as a non member function
and apparentley
this is "against" the OOP programming
because the <code>clearEverything()</code>
 
meh OOP is overrated
 
encapsulates less
ok, but why would that be a bad idea?
 
it isn't really, except that the name isn't the greatest and logically it should be part of the WebBrowser interface
 
both choices are bad really
 
2:33 PM
why?
 
if you have a subclass of WebBrowser that also has another thing you could clear, calling clearEverything(derived_instance); wouldn't clear that thing
with derived you could at least override it, but that's also bad since people can forget to do it
 
or do it badly
 
if you move history to a separate object, which can be then passed as a dependency to some kind of "data holder object", then this "data holder object" could call clear() on everything
 
is that the reason to prefer a not member function?
instead of a member one?
or "a" reason?
 
in your example your WebBrowser simply does too much
 
2:37 PM
I report what I don't actually understand
Object-oriented principles dictate that data and the functions that
operate on them should be bundled together, and that suggests that
the member function is the better choice. Unfortunately, this suggestion
is incorrect. It’s based on a misunderstanding of what being
object-oriented means. Object-oriented principles dictate that data
should be as encapsulated as possible. Counterintuitively, the member
function clearEverything actually yields less encapsulation than the
non-member clearBrowser. Furthermore, offering the non-member
it's the point "clearEverything actually yields less encapsulation than the
non-member clearBrowser" that I don't actually get
there's then this small piece
(after explaining why data members in general should be private)
Given a
choice between a member function (which can access not only the private
data of a class, but also private functions, enums, typedefs, etc.)
and a non-member non-friend function (which can access none of
these things) providing the same functionality, the choice yielding
greater encapsulation is the non-member non-friend function,
because it doesn’t increase the number of functions that can access the private parts of the class
 
It's like the author is trying to say, "abstraction is leaky and as such the leak must be plugged"
 
I do still struggle a bit
I think it's trying to point out some subtle point I can't quite understand
 
IMO it's OOP purism that is kinda useless to worry about when trying to get stuff out the door
just make the member clearAllCaches and be done with it
 
I think that was a specific example, he wasn't trying to explain how to design a web browser (or trying to explain how following OOP principles)
 
once you have a few years of experience with your own opinions and frustrations with past decisions, you will have a better view about what's important and what's useless pedantism
 
2:49 PM
@user8469759 Here's the rationale arguing for non-member functions gotw.ca/gotw/084.htm
 
is there a specific part of that page you're pointing out?
Ok, I'm reading through
there's a specific part mentioning the book
 
generally the whole page is arguing for this, but if you want specifics, then there's the advantages/disadvantages part in the middle
Ctrl+F "members vs. nonmembers"
 
what's the meaning of "responsability" in the context of software engineering?
 
don't create more work for future people working with your code
 
I don't think it would be possible to have a precise definition for that, but it pretty much means what you're expecting it to mean
 
2:58 PM
oh that kind of responability
 
3:16 PM
I'm not sure I've understood that link
So it is preferrable (when the functionality is equivalent) to declare functions as non member (non friend) functions
because of the monolithic structure of the class?
 
which part is the one you haven't understood
 
basically the guy starts with that huge class
and then he says at some point
 
the point is that if a thing can be implemented in terms of another thing, it can be a non-member
 
ok, but as a best practice
it is my understanding that it HAS TO be non-member
 
nothing HAS TO be anything
 
3:27 PM
this can also be useful (at least to me)
 
it helps if you understand the reasoning for excessive encapsulation: reducing amount of code that can access some specific data will reduce the likelihood of bugs with that data
 
That's what he's saying in the "encapsulation" section
 
the Point example is fairly stupid really
 
why is that?
 
point should be POD
 
3:32 PM
realistically no one will be able to change the Point class to be computed or use a database lookup
database lookup assumes there's a database connection somewhere
 
what kind of example should he present in order to make the point?
 
dunno, I think some kind of game entity would be better, but it's domain specific
 
so you think the point is trying to make is correct but he's using the wrong examples
I'm still not sure, say you have a class C, with private data members, and N methods, say you have implemented externally many other functions that are somehow related to C
to interact with C they need to use the methods of C
if for some reason i change the private members
I could possibly break the methods
and if the methods are broken the external functions are also broken
I can then fix the methods
but this doesn't guarantee that my external functions will be automatically fixed
 
3:48 PM
it will if regression tests against the member functions all pass
 
what do you mean by "regression tests"?
 
@user8469759 that's what unit tests are for
 
unittests that passed before the change
 
also non-member vs member changes literally nothing here
 
can you elaborate a bit more? I understand this question is probably annoying
but I would be grateful if someone would help me understanding
why "non-member vs member" changes nothing?
 
3:51 PM
hang on, this will be a long rant
A class presents what's commonly called "interface" or "contract" or "specification". This specification describes every element. What it's supposed to happen after the function call (so called postconditions), what are the requirements that must be satisfied before the function call (so called preconditions), and what generally the class supposed to maintain (so called class invariants)
I'll use std::string to explain this
std::string has a class invariant that the character after the last one is '\0' to make it usable with legacy C function that take null terminated strings
std::string::operator[] has a precondition that the index must be less than the size, which is described in terms of .size() member function
generally if the precondition is not satisfied, you get undefined behaviour
it's literally "your warranty is void if you do this"
if you present a class, you also present a contract of a class.
 
ok but, because of this
this means that any member function I do declare in a class
I have to design o declare pre/post conditions and invariant
 
the contract also helps wrt versioning
 
and because of this I should have much more control than non member functions
 
the users can be sure that the contract won't change
if you make a breaking change to your contract, this is either a bug, or you should bump a major version
of course if you change your contract often, users can have problem with that
the less member functions you have, the smaller is the contract surface of the class
 
say you change the contract of a small class with few member functions
why this allows to have (likely) less error propagation
for all the clients of that class
you should at least change the other modules interface potentially
and if not the interface, at least the implementation
 
4:06 PM
what
 
you explained to me (please correct me if I'm wrong) that a class embodies in his design
 
if you broke the contract, then, of course, everything will be broken
 
such precondition/postcondition/invariantes (which defines the contract)
 
because the rest of the world expects the previous contract, not the new one
if you don't break the contract, then everything that doesn't rely on the implementation details, will not be broken
 
ok, I can understand that
but why making a function as non member reduce the error propagation in case of changing the class implementation?
how is this related to the contract
 
4:09 PM
5 mins ago, by milleniumbug
the less member functions you have, the smaller is the contract surface of the class
 
so is that the point then? just having a small interface with these specifications you were talking about?
 
it's not "just" having a small interface
let's say you want to make a string class, like std::string, because there's something in std::string that makes it unsuitable for your project
now you have to implement all the 110 methods
but as the link above mentions, only half of them are actually needed to be members
find_first_of is essentially std::find
and std::find can operate on std::vector, std::list, std::deque, std::string, ...
 
ok hang on
but isn't that case a kind of "factoring"?
 
isn't that a different thing from the encapsulation
you basically make the std::find operating on templates, so you can reuse the algorithm
say instead you have a method of string, that works on the data member straightforward
as you said if you change the data member you need to change such method (call it m1)
say you actually don't need such method to belong the class
you implement the method outside as a function
say f1, but you need to use a method m2 to change, maybe the data member
now say for any reason you change the data member, so you need probably to change m2, and in turns you need to change f1 as well
I don't see the gain here
 
4:16 PM
the goal of encapsulation is to reduce the area of code that may need to change if an internal changes
 
59 mins ago, by milleniumbug
the point is that if a thing can be implemented in terms of another thing, it can be a non-member
your m1 and f1 aren't implemented in terms of another thing if they touch a private data member
 
no, f1 is implemented in terms of m2
 
then you should be able to fix m2 without changing it's contract
 
well then see above with the contract breaking
 
but I was posing the problem a posteriori
because in the beginning changing something would have involved at least the modification of two methods (m1 and m2)
a posteriori
the change of something
could imply the need of changing of m2 and f1
still two functions to look after
 
4:23 PM
I have no idea what you're about now
either you break the contract or you don't
 
if you can't fix m2 without breaking its contract then you are locked into the previous implementation
 
Can I do a small step back? to be sure we are on the same page?
 
for example, std::unordered_set has a concept that every element has referential consistency. Which means that a pointer to an element will remain valid for as long as the element is in the set.
This requires that every element gets allocated in a separate node.
 
@user8469759 hmmm, is it that m2 wasn't previously in the class contract? because I've assumed it is
 
my assumption was that both m1 and m2 are in the class, but later I decide to move m1 as an external function f1 (with the justifications I've tried to give).
I should have stated that, I'm sorry
 
4:30 PM
if you change from class A { void m1(); }; to class A { void m2(); }; void f1(A& a) { /* something before */ a.m2(); /* something after */ };, then indeed, you are not in the better situation than before
 
sorry sorry sorry
ok
Now, I'm trying to come up with a simple example that JUSTIFY instead to move a method outside the class
(justifies, sorry for the typo)
 
I can implement std::string::find with
std::size_t f(const std::string& haystack, const std::string& needle)
{
	auto it = std::search(haystack.begin(), haystack.end(), needle.begin(), needle.end());
	if(it == haystack.end())
		return npos;
	else
		return haystack.begin() - it;
}
 
and as long as the contracts for begin and end stay the same then it will keep working no matter the internals of std::string
 
So the point is you should prefer external functions to member functions as long as the behaviour can be expressed in terms of that contract/interface
 
pretty much
 
4:40 PM
because if that is true there's no point in keeping them as member functions
(unless maybe there's some efficiency issue etc, but that's a different matter probably_
)
 
the fun part is that now the C++17's std::search gets the performance extensions, not std::string::find
IOW I can replace the function above to use Boyer-Moore algorithm instead of naive one with
std::size_t f(const std::string& haystack, const std::string& needle)
{
	auto it = std::search(haystack.begin(), haystack.end(), make_boyer_moore_searcher(needle.begin(), needle.end())); // C++17's searchers
	if(it == haystack.end())
		return npos;
	else
		return haystack.begin() - it;
}
 
one of the efficiency issues could be sorting, sorting a linked list can be done very efficiently in constant memory. Sorting an array often needs O(log n) or O(n) extra memory or is less efficient.
 
this discussion destroyed me
literally
uff
one last question (completely different)
Say I have a class like
template<int I>
class MyClass {
    public:
       MyClass(int k);
       template<int J>
       MyClass<Max(i,j)> operator+(const MyClass<I>& x, const MyClass<J>& y);
    private:
      //something
};
(It's a bit pseudocode)
is there a way to specifcy
that when not specified an integer should be casted to (for example) MyClass<32>?
so I can do stuff like
int x = 10;
MyClass<20> y(20);

x + y; //x is an integer whose I don't know the destination MyClass type
 
4:56 PM
not directly
 
you can add an additional overload to operator+
 
You mean something like
 
oh wait
let me re-read this
 
yes, you need to add additional overloads
 
4:58 PM
I'd say at least two overloaf
(overload*) one for left operand and one for right operand
there's no other clever way for doing that
because this would mean for each operator /*+-% (for example) I have to provide 15 implementations
 
implicit conversions can't do since you convert from built-in type to non-built in one, and implicit constructors can't do this since you already have one for every MyClass<I>
we could go down the SFINAE hole, but this may be too obscure
 
I would give it a go, If I would understand how it works
 
tbh now that I think about this, it would save you from writing one overload, (IOW 2 instead of 3), at the cost of that overload being complicated SFINAE conversions
 
is it that complicated?
a type conversion using sfinae
I thought maybe there was some kind of trick that would allow to state "when you don't know call this constructor"
or anyway cast to that type
 
maybe it will be simpler with some changes to the MyClass's interface
let me see
 
meta programming 4ever
is it C++11?
or do I need more or equal than C++14?
 
it's C++11
 
ah ok
it's amazing
I have a code that look like that and basically I don't know how to simplify
is too redundant
so I'd prefer metaprogramming rather than writing down many version of the same thing
 
now that I think about it, the only part which actually uses C++11 for anything is the one with std::integral_constant
trailing return type is not needed
and even std::integral_constant can be emulated
oh, and it's not strictly needed either
ok, Max is C++11 constexpr
it's also not strictly needed
 
In your case
Your constructor doesn't do anything
 
5:25 PM
yes, in my case
well, yeah
it was an example
 
template<typename T>
struct DegreeTraits
{
	typedef typename T::Degree Degree;
};

template<>
struct DegreeTraits<int>
{
	typedef std::integral_constant<int, 32> Degree;
};
what's the purpose of DegreeTraits?
 
int does not have a member Degree type so we need to dispatch it elsewhere
note that this can accidentally match different types which happen to have a Degree member type
we can avoid that with more code
that is, 3 lines of it
 
I suppose with some kind of enable if
 
oh, it was even simpler than I expected
and I can remove the member Degree type too
 
template<typename T>
struct DegreeTraits
{

};

template<>
struct DegreeTraits<int>
{
	typedef std::integral_constant<int, 32> Degree;
};

template<int I>
struct DegreeTraits<MyClass<I>>
{
	typedef std::integral_constant<int, I> Degree;
};
I believe these three are the key
so If I do DegreeType<Bool> it wouldn't do anything (probably complation error)
 
5:34 PM
yes
 
If I do Degree
by defalut it would give me the constant 32
in the other cases it would give me the wanted constant
 
DegreeTraits<int>::Degree::value gives you 32
otherwise if it's DegreeTraits<MyClass<whatever>>::Degree::value it gives you whatever the MyClass has
otherwise it has no member
and as such, it SFINAEs out the operator+ overload
which means it doesn't participate in overload resolution
 
there's one think I don't understand
is std::integral_constant
literally a constant
?
and if yes
I'm not sure how you're using the typdef
 
std::integral_constant is template<typename T, T Value> struct integral_constant { static constexpr T value = Value; }; but with some frills
 
ah ok, this is why you can extract the field Value
 
5:38 PM
you could use static constexpr int degree = 32; instead
 
template<typename T, typename U>
auto operator+(const T& x, const U& y) -> MyClass<Max(DegreeTraits<T>::Degree::value, DegreeTraits<U>::Degree::value)>
is there a specific reason you used the keyword "auto" here?
I usually go for the classic syntax
type + signature
 
initially I thought I would need it (to access the x and y parameters), but in the end I didn't
and I was too lazy to change it back
 
XD
so you could write something like
template<typename T, typename U>
 MyClass<Max(DegreeTraits<T>::Degree::value, DegreeTraits<U>::Degree::value)> operator+(const T& x, const U& y)
or something like
template<int I, int J>
MyClass<Max(DegreeTraits<I>::Degree::value, DegreeTraits<J>::Degree::value)> operator+(const MyClass<I>& x, const MyClass<J>& y)
would that work?
 
no the latter one won't
 
how so?
 
5:41 PM
I wanted to ask a fast question. My function take int **x as a parameter while i pass multi-dimensional array; not array of pointers to int array. Am i able to pass it like that?
 
because you can't have deduction and conversions at the same time
@Siliproksi can't pass int a[20][50] to a function that takes int**
 
@milleniumbug Oh, why?
 
372
Q: How do I use arrays in C++?

fredoverflowC++ inherited arrays from C where they are used virtually everywhere. C++ provides abstractions that are easier to use and less error-prone (std::vector<T> since C++98 and std::array<T, n> since C++11), so the need for arrays does not arise quite as often as it does in C. However, when you read l...

 
but can I restrict the types using something else?
I mean in my case they would be or MyClass<I> or int
 
they're already restricted in the first function
DegreeTraits restricts them
 
5:46 PM
really?
I don't see how
 
because DegreeTraits<long>::Degree won't compile
 
why not?
ah ok
it works just for integers
you declared otherwise the struct empty
and the types of templates of the function are restricted by the substitution in the return value
is that correct?
 
yes
if you substitute MyClass<whatever> for T or U it will work
if you substitute int for T or U it will work
otherwise it won't because DegreeTraits won't have a member Degree type
 
I'm realizing now that your templates functions (you structs basically) on take the type int while the other one takes as argument an integer, used later to dispatch the MyClass<I> type
I'll give it a go tomorrow
thank you so much
bye bye
 
now that I look at it, you'd also need to convert the ints
because now the function accepts both ints and MyClass
 
5:53 PM
what do you mean?
 
T can be an int, or MyClass<I>
you'd probably want to convert the int to MyClass<32> first
 
@milleniumbug I read the answer of that post, and i am quite confused now. I thought int(*)[8] is array of 8 pointers, and each one points to int array (the array you tell them to point to), also here is another reason why i think like that: stackoverflow.com/questions/936687/…. While he says (in the answer) that int(*)[8] is pointer to an int array that is 8 elements wide.
 
@milleniumbug Oh sorry, i mixed up int *x[8] and int x(*)[8]. I will read the rest of the post you sent me, thanks :) By the way, int *x[8] is what i thought int x(*)[8] is . Right?
 
@Siliproksi yes
 
6:06 PM
@milleniumbug Sorry to bother you, it was anyways explained in the post. I should just keep up. Im sometimes too much impatient.
 

« first day (225 days earlier)      last day (2631 days later) »