Why does compiler give an error on line 1, even though copy constructor will not be called in line 1 and the error vanishes if copy constructor signature is declared as const?
class A {
int i;
public:
A(int n) :
i(n) {
cout << "A ctor" << endl;
}
A(A& a) :
i(a.i) {
cout << "A c-ctor" << endl;
}
~A() {
}
};
int main() {
A a1(1);
A a2 = 2; // line 1
A a3 = a1; // line 2
}
//The above code was compiled with MinGW
This is an effect of implicit constructor call. Try to add "explicit" clause before the constructor declaration
....
explicit A(int n) :
i(n) {
cout << "A ctor" << endl;
}
....
Given that, compiler would complain like "conversion from 'int' to non-scalar type 'A' requested". This sheds some light why:
A a2 = 2; // line 1, original, fails on explicit construction
A a2 = A(2); // line 1, auto-substituted by compiler if implicit construction allowed
So, if our compiler can find a way to automatically convert one type to another via constructor call, it auto-instantiates it here.
Also this gives the answer "why 'const' required for copy constructor":
A a2 = A(2);
A a2(A(2)); // default implementation of '= operator'
Here, A(2) is temporary object. Thus, compiler would try to get non-const reference to it and fails (because it's rvalue - otherwise you can try to change something that will die at the end of line).
Related
what is the difference between rint and nearbyint?
Will they give some different output in some cases?
If not, is there a difference in the concept of calculations?
Since these are both C functions, we can check the man page for both of these. An excerpt:
The nearbyint() functions round their argument to an integer value in floating-point format, using the current rounding direction (see fesetround(3)) and without raising the inexact exception.
The rint() functions do the same, but will raise the inexact exception (FE_INEXACT, checkable via fetestexcept(3)) when the result differs in value from the argument.
In other words, rint allows you to do error checking while nearbyint does not. An example of error-checking:
#include <iostream>
#include <cmath>
#include <cfenv>
int main()
{
std::feclearexcept(FE_INEXACT);
double a = std::rint(93819.249);
if (!std::fetestexcept(FE_INEXACT))
std::cerr << "Bad rounding\n";
else
std::cout << a << '\n';
}
I am trying to add 2 char arrays in cuda, but nothing is working.
I tried to use:
char temp[32];
strcpy(temp, my_array);
strcat(temp, my_array_2);
When I used this in kernel - I am getting error : calling a __host__ function("strcpy") from a __global__ function("Process") is not allowed
After this, I tried to use these functions in host, not in kernel - no error,but after addition I am getting strange symbols like ĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶĶ.
So, how I can add two ( or more ) char arrays in CUDA ?
So, how I can add two ( or more ) char arrays in CUDA ?
write your own functions:
__device__ char * my_strcpy(char *dest, const char *src){
int i = 0;
do {
dest[i] = src[i];}
while (src[i++] != 0);
return dest;
}
__device__ char * my_strcat(char *dest, const char *src){
int i = 0;
while (dest[i] != 0) i++;
my_strcpy(dest+i, src);
return dest;
}
And while we're at it, here is strcmp
As the error message explains, you are trying to call host functions ("CPU functions") from a global kernel ("GPU function"). Within a global kernel you only have access to functions provided by the CUDA runtime API, which doesn't include the C standard library (where strcpy and strcat are defined).
You have to create your own str* functions according to what you want to do. Do you want to concatenate an array of chars in parallel, or do it serially in each thread?
Can someone help me to understand how i need to send the parameters to the function "lora_rf_config" ? Thank you so much !
I try with:
char cfgred[7][10]={'lora_rf_config','915000000','10','0','1','8','14'};
lora_rf_config(7,&cfgred);
The function that im trying to use is:
static void lora_rf_config(int argc, char *argv[])
{
if (argc == 1) {
e_printf("OK%d,%d,%d,%d,%d,%d\r\n", g_lora_config.lorap2p_param.Frequency,
g_lora_config.lorap2p_param.Spreadfact,
g_lora_config.lorap2p_param.Bandwidth,
g_lora_config.lorap2p_param.Codingrate,
g_lora_config.lorap2p_param.Preamlen,
g_lora_config.lorap2p_param.Powerdbm );
return;
} else {
if (argc != 7) {
out_error(RAK_ARG_ERR);
return;
}
if (!(CHECK_P2P_FREQ(atoi(argv[1])) &&
CHECK_P2P_SF(atoi(argv[2])) &&
CHECK_P2P_BDW(atoi(argv[3])) &&
CHECK_P2P_CR(atoi(argv[4])) &&
CHECK_P2P_PREMLEN(atoi(argv[5])) &&
CHECK_P2P_PWR(atoi(argv[6])))) {
out_error(RAK_ARG_ERR);
return;
}
if (read_partition(PARTITION_0, (char *)&g_lora_config, sizeof(g_lora_config)) < 0) {
out_error(RAK_RD_CFG_ERR);
return;
}
g_lora_config.lorap2p_param.Frequency = atoi(argv[1]);
g_lora_config.lorap2p_param.Spreadfact = atoi(argv[2]);
g_lora_config.lorap2p_param.Bandwidth = atoi(argv[3]);
g_lora_config.lorap2p_param.Codingrate = atoi(argv[4]);
g_lora_config.lorap2p_param.Preamlen = atoi(argv[5]);
g_lora_config.lorap2p_param.Powerdbm = atoi(argv[6]);
write_partition(PARTITION_0, (char *)&g_lora_config, sizeof(g_lora_config));
e_printf("OK\r\n");
}
return;
}
The error that i got is:
..\..\..\src\application\RAK811\app.c(107): error: #26: too many characters in character constant
char cfgred[7][10]={'lora_rf_config','915000000','10','0','1','8','14'};
I dont have experience with this kind of arguments.
Thank you for your time.
lora_rf_config expects same arguments than main function: array of pointers to strings, and its length.
Strings in C are pointers to char, where the char buffer they point to has terminating NUL character (if NUL char is missing, then it's not a string, just a character array). In other words, there is no string type in C, but stringiness is determined by the actual data in the char array or buffer. Using "" string literal creates a string, IOW it adds that terminating NUL char in addition to what you write.
// cfgred is array([) of 7 pointers(*) to char.
// Note: string literals are read-only, so you must not modify these
// strings. If you want a modifiable string, this would be a bit more complex,
// but I think this is out of the scope of your question.
char *cfgred[7] = { "lora_rf_config" , "915000000", "10","0", "1", "8", "14"};
// you can get the number of elements in array by dividing its sizeof size (bytes)
// with the size of it's elements in bytes. Just make sure cfgred here is array...
// in the function it is pointer already (arrays get converted to pointers, so
// you can't do this inside the function, you have to do it where you still have
// the original array
int cfgred_len = sizeof cfgred / sizeof(cfgred[0]);
// when you pass array to function, it is automatically converted to pointer,
// so you must not use & when passing an array like this, otherwise types don't
// match
lora_rf_config(cfgred_len, cfgred);
As a side note, always turn on compiler warnings... They help you a lot, fix them. For gcc and clagn, use -Wall -Wextra, for Visual Studio use /W3 or prefereably /W4. And then fix any warnings you get, because they are probably something that doesn't do what you expect.
Your initialization is not done correctly, try changing
char cfgred[7][10]={'lora_rf_config','915000000','10','0','1','8','14'};
into
char cfgred[7][16]={"lora_rf_config","915000000","10","0","1","8","14"};
So this is more of a theoretical question. C++ and languages (in)directly based on it (Java, C#, PHP) have shortcut operators for assigning the result of most binary operators to the first operand, such as
a += 3; // for a = a + 3
a *= 3; // for a = a * 3;
a <<= 3; // for a = a << 3;
but when I want to toggle a boolean expression I always find myself writing something like
a = !a;
which gets annoying when a is a long expression like.
this.dataSource.trackedObject.currentValue.booleanFlag =
!this.dataSource.trackedObject.currentValue.booleanFlag;
(yeah, Demeter's Law, I know).
So I was wondering, is there any language with a unary boolean toggle operator that would allow me to abbreviate a = !a without repeating the expression for a, for example
!=a;
// or
a!!;
Let's assume that our language has a proper boolean type (like bool in C++) and that a is of that type (so no C-style int a = TRUE).
If you can find a documented source, I'd also be interested to learn whether e.g. the C++ designers have considered adding an operator like that when bool became a built-in type and if so, why they decided against it.
(Note: I know that some people are of the opinion that assignment should not use
= and that ++ and += are not useful operators but design flaws; let's just assume I'm happy with them and focus on why they would not extend to bools).
Toggling the boolean bit
... that would allow me to abbreviate a = !a without repeating the
expression for a ...
This approach is not really a pure "mutating flip" operator, but does fulfill your criteria above; the right hand side of the expression does not involve the variable itself.
Any language with a boolean XOR assignment (e.g. ^=) would allow flipping the current value of a variable, say a, by means of XOR assignment to true:
// type of a is bool
a ^= true; // if a was false, it is now true,
// if a was true, it is now false
As pointed out by #cmaster in the comments below, the above assumes a is of type bool, and not e.g. an integer or a pointer. If a is in fact something else (e.g. something non-bool evaluating to a "truthy" or "falsy" value, with a bit representation that is not 0b1 or 0b0, respectively), the above does not hold.
For a concrete example, Java is a language where this is well-defined and not subject to any silent conversions. Quoting #Boann's comment from below:
In Java, ^ and ^= have explicitly defined behavior for booleans
and for integers
(15.22.2.
Boolean Logical Operators &, ^, and | ), where either both sides
of the operator must be booleans, or both sides must be integers.
There's no silent conversion between those types. So it's not going to
silently malfunction if a is declared as an integer, but rather,
give a compile error. So a ^= true; is safe and well-defined in
Java.
Swift: toggle()
As of Swift 4.2, the following evolution proposal has been accepted and implemented:
SE-0199: Adding toggle to Bool
This adds a native toggle() function to the Bool type in Swift.
toggle()
Toggles the Boolean variable’s value.
Declaration
mutating func toggle()
Discussion
Use this method to toggle a Boolean value from true to false or
from false to true.
var bools = [true, false]
bools[0].toggle() // bools == [false, false]
This is not an operator, per se, but does allow a language native approach for boolean toggling.
In C++ it is possible to commit the Cardinal Sin of redefining the meaning of operators. With this in mind, and a little bit of ADL, all we need to do in order to unleash mayhem on our user base is this:
#include <iostream>
namespace notstd
{
// define a flag type
struct invert_flag { };
// make it available in all translation units at zero cost
static constexpr auto invert = invert_flag{};
// for any T, (T << invert) ~= (T = !T)
template<class T>
constexpr T& operator<<(T& x, invert_flag)
{
x = !x;
return x;
}
}
int main()
{
// unleash Hell
using notstd::invert;
int a = 6;
std::cout << a << std::endl;
// let confusion reign amongst our hapless maintainers
a << invert;
std::cout << a << std::endl;
a << invert;
std::cout << a << std::endl;
auto b = false;
std::cout << b << std::endl;
b << invert;
std::cout << b << std::endl;
}
expected output:
6
0
1
0
1
As long as we include assembly language...
FORTH
INVERT for a bitwise complement.
0= for a logical (true/false) complement.
Decrementing a C99 bool will have the desired effect, as will incrementing or decrementing the bit types supported in some tiny-microcontroller dialects (which from what I've observed treat bits as single-bit wide bitfields, so all even numbers get truncated to 0 and all odd numbers to 1). I wouldn't particularly recommend such usage, in part because I'm not a big fan of the bool type semantics [IMHO, the type should have specified that a bool to which any value other than 0 or 1 is stored may behave when read as though it holds an Unspecified (not necessarily consistent) integer value; if a program is trying to store an integer value that isn't known to be 0 or 1, it should use !! on it first].
Assembly language
NOT eax
See https://www.tutorialspoint.com/assembly_programming/assembly_logical_instructions.htm
I'm assuming you're not going to be choosing a language based solely upon this :-) In any case, you can do this in C++ with something like:
inline void makenot(bool &b) { b = !b; }
See the following complete program for example:
#include <iostream>
inline void makenot(bool &b) { b = !b; }
inline void outBool(bool b) { std::cout << (b ? "true" : "false") << '\n'; }
int main() {
bool this_dataSource_trackedObject_currentValue_booleanFlag = false;
outBool(this_dataSource_trackedObject_currentValue_booleanFlag);
makenot(this_dataSource_trackedObject_currentValue_booleanFlag);
outBool(this_dataSource_trackedObject_currentValue_booleanFlag);
makenot(this_dataSource_trackedObject_currentValue_booleanFlag);
outBool(this_dataSource_trackedObject_currentValue_booleanFlag);
}
This outputs, as expected:
false
true
false
PostScript, being a concatenative, stack-oriented language like Forth, has a unary toggle, not. The not operator toggles the value on top of the stack. For example,
true % push true onto the stack
not % invert the top of stack
% the top of stack is now false
See the PostScript Language Reference Manual (pdf), p. 458.
Visual Basic.Net supports this via an extension method.
Define the extension method like so:
<Extension>
Public Sub Flip(ByRef someBool As Boolean)
someBool = Not someBool
End Sub
And then call it like this:
Dim someVariable As Boolean
someVariable = True
someVariable.Flip
So, your original example would look something like:
me.DataSource.TrackedObject.CurrentValue.BooleanFlag.Flip
This question is indeed interesting from a purely theoretical standpoint. Setting aside whether or not a unary, mutating boolean toggle operator would be useful, or why many languages have opted to not provide one, I ventured on a quest to see whether or not it indeed exists.
TL;DR apparently no, but Swift lets you implement one. If you'd only like to see how it's done, you can scroll to the bottom of this answer.
After a (quick) search to features of various languages, I'd feel safe to say that no language has implemented this operator as a strict mutating in-place operation (do correct me if you find one). So the next thing would be to see if there are languages that let you build one. What this would require is two things:
being able to implement (unary) operators with functions
allowing said functions to have pass-by-reference arguments (so that they may mutate their arguments directly)
Many languages will immediately get ruled out for not supporting either or both of these requirements. Java for one does not allow operator overloading (or custom operators) and in addition, all primitive types are passed by value. Go has no support for operator overloading (except by hacks) whatsoever. Rust only allows operator overloading for custom types. You could almost achieve this in Scala, which let's you use very creatively named functions and also omit parentheses, but sadly there's no pass-by-reference. Fortran gets very close in that it allows for custom operators, but specifically forbids them from having inout parameters (which are allowed in normal functions and subroutines).
There is however at least one language that ticks all the necessary boxes: Swift. While some people have linked to the upcoming .toggle() member function, you can also write your own operator, which indeed supports inout arguments. Lo and behold:
prefix operator ^
prefix func ^ (b: inout Bool) {
b = !b
}
var foo = true
print(foo)
// true
^foo
print(foo)
// false
In Rust, you can create your own trait to extend the types that implement the Not trait:
use std::ops::Not;
use std::mem::replace;
trait Flip {
fn flip(&mut self);
}
impl<T> Flip for T
where
T: Not<Output = T> + Default,
{
fn flip(&mut self) {
*self = replace(self, Default::default()).not();
}
}
#[test]
fn it_works() {
let mut b = true;
b.flip();
assert_eq!(b, false);
}
You can also use ^= true as suggested, and in the case of Rust, there is no possible issue to do this because false is not a "disguised" integer like in C or C++:
fn main() {
let mut b = true;
b ^= true;
assert_eq!(b, false);
let mut b = false;
b ^= true;
assert_eq!(b, true);
}
In Python
Python supports such functionality, if the variable has bool type (which is True or False) with the exclusive or (^=) operator:
a = False
a ^= True
print(a) # --> True
a ^= True
print(a) # --> False
In C#:
boolean.variable.down.here ^= true;
The boolean ^ operator is XOR, and XORing with true is the same as inverting.
I have the following class (this is not my real class, but just for illustration purposes):
class Number {
public:
Number() : value_(0) {}
explicit Number(int v) : value_(v) {}
Number(const Number & other){
value_ = other.value_;
}
Number& operator=(const int & v){
value_ = v;
return *this;
}
private:
int value_;
};
I can do the following and they all work correctly:
void test_ok(){
Number x(3);
Number y = Number(3);
Number y2(x);
Number y3 = x;
Number u;
u = 3;
}
However, the following gives this compiler error: no suitable constructor exists to convert from "int" to "Number"
void test_error(){
Number z = 3;
}
If I comment the word "explicit" from the second constructor, then the compiler error is gone and apparently the automatic conversion works fine. Since I would like to keep the keyword "explicit", which constructor am I missing?
Thanks in advance!
The explicit keyword prohibits implicit automatic typecasting. In your test Number z = 3 you're doing exactly that - implicit typecasting, from an int (3) to a Number. The compiler rightfully prohibits that.
If you want to keep the keyword explicit then you'll have to construct the Number object as Number(3) (as you'd already noticed and written).
In short, there is no other constructor that you can use if you want to keep the explicit keyword. Whatever you do, implicit typecasts will be prohibited.