How to Pass Parameters Correctly

How to pass parameters correctly?

THE MOST IMPORTANT QUESTION FIRST:

Are there any best practices of how to send parameters in C++ because I really find it, let's say, not trivial

If your function needs to modify the original object being passed, so that after the call returns, modifications to that object will be visible to the caller, then you should pass by lvalue reference:

void foo(my_class& obj)
{
// Modify obj here...
}

If your function does not need to modify the original object, and does not need to create a copy of it (in other words, it only needs to observe its state), then you should pass by lvalue reference to const:

void foo(my_class const& obj)
{
// Observe obj here
}

This will allow you to call the function both with lvalues (lvalues are objects with a stable identity) and with rvalues (rvalues are, for instance temporaries, or objects you're about to move from as the result of calling std::move()).

One could also argue that for fundamental types or types for which copying is fast, such as int, bool, or char, there is no need to pass by reference if the function simply needs to observe the value, and passing by value should be favored. That is correct if reference semantics is not needed, but what if the function wanted to store a pointer to that very same input object somewhere, so that future reads through that pointer will see the value modifications that have been performed in some other part of the code? In this case, passing by reference is the correct solution.

If your function does not need to modify the original object, but needs to store a copy of that object (possibly to return the result of a transformation of the input without altering the input), then you could consider taking by value:

void foo(my_class obj) // One copy or one move here, but not working on
// the original object...
{
// Working on obj...

// Possibly move from obj if the result has to be stored somewhere...
}

Invoking the above function will always result in one copy when passing lvalues, and in one moves when passing rvalues. If your function needs to store this object somewhere, you could perform an additional move from it (for instance, in the case foo() is a member function that needs to store the value in a data member).

In case moves are expensive for objects of type my_class, then you may consider overloading foo() and provide one version for lvalues (accepting an lvalue reference to const) and one version for rvalues (accepting an rvalue reference):

// Overload for lvalues
void foo(my_class const& obj) // No copy, no move (just reference binding)
{
my_class copyOfObj = obj; // Copy!
// Working on copyOfObj...
}

// Overload for rvalues
void foo(my_class&& obj) // No copy, no move (just reference binding)
{
my_class copyOfObj = std::move(obj); // Move!
// Notice, that invoking std::move() is
// necessary here, because obj is an
// *lvalue*, even though its type is
// "rvalue reference to my_class".
// Working on copyOfObj...
}

The above functions are so similar, in fact, that you could make one single function out of it: foo() could become a function template and you could use perfect forwarding for determining whether a move or a copy of the object being passed will be internally generated:

template<typename C>
void foo(C&& obj) // No copy, no move (just reference binding)
// ^^^
// Beware, this is not always an rvalue reference! This will "magically"
// resolve into my_class& if an lvalue is passed, and my_class&& if an
// rvalue is passed
{
my_class copyOfObj = std::forward<C>(obj); // Copy if lvalue, move if rvalue
// Working on copyOfObj...
}

You may want to learn more about this design by watching this talk by Scott Meyers (just mind the fact that the term "Universal References" that he is using is non-standard).

One thing to keep in mind is that std::forward will usually end up in a move for rvalues, so even though it looks relatively innocent, forwarding the same object multiple times may be a source of troubles - for instance, moving from the same object twice! So be careful not to put this in a loop, and not to forward the same argument multiple times in a function call:

template<typename C>
void foo(C&& obj)
{
bar(std::forward<C>(obj), std::forward<C>(obj)); // Dangerous!
}

Also notice, that you normally do not resort to the template-based solution unless you have a good reason for it, as it makes your code harder to read. Normally, you should focus on clarity and simplicity.

The above are just simple guidelines, but most of the time they will point you towards good design decisions.


CONCERNING THE REST OF YOUR POST:

If i rewrite it as [...] there will be 2 moves and no copy.

This is not correct. To begin with, an rvalue reference cannot bind to an lvalue, so this will only compile when you are passing an rvalue of type CreditCard to your constructor. For instance:

// Here you are passing a temporary (OK! temporaries are rvalues)
Account acc("asdasd",345, CreditCard("12345",2,2015,1001));

CreditCard cc("12345",2,2015,1001);
// Here you are passing the result of std::move (OK! that's also an rvalue)
Account acc("asdasd",345, std::move(cc));

But it won't work if you try to do this:

CreditCard cc("12345",2,2015,1001);
Account acc("asdasd",345, cc); // ERROR! cc is an lvalue

Because cc is an lvalue and rvalue references cannot bind to lvalues. Moreover, when binding a reference to an object, no move is performed: it's just a reference binding. Thus, there will only be one move.


So based on the guidelines provided in the first part of this answer, if you are concerned with the number of moves being generated when you take a CreditCard by value, you could define two constructor overloads, one taking an lvalue reference to const (CreditCard const&) and one taking an rvalue reference (CreditCard&&).

Overload resolution will select the former when passing an lvalue (in this case, one copy will be performed) and the latter when passing an rvalue (in this case, one move will be performed).

Account(std::string number, float amount, CreditCard const& creditCard) 
: number(number), amount(amount), creditCard(creditCard) // copy here
{ }

Account(std::string number, float amount, CreditCard&& creditCard)
: number(number), amount(amount), creditCard(std::move(creditCard)) // move here
{ }

Your usage of std::forward<> is normally seen when you want to achieve perfect forwarding. In that case, your constructor would actually be a constructor template, and would look more or less as follows

template<typename C>
Account(std::string number, float amount, C&& creditCard)
: number(number), amount(amount), creditCard(std::forward<C>(creditCard)) { }

In a sense, this combines both the overloads I've shown previously into one single function: C will be deduced to be CreditCard& in case you are passing an lvalue, and due to the reference collapsing rules, it will cause this function to be instantiated:

Account(std::string number, float amount, CreditCard& creditCard) : 
number(num), amount(amount), creditCard(std::forward<CreditCard&>(creditCard))
{ }

This will cause a copy-construction of creditCard, as you would wish. On the other hand, when an rvalue is passed, C will be deduced to be CreditCard, and this function will be instantiated instead:

Account(std::string number, float amount, CreditCard&& creditCard) : 
number(num), amount(amount), creditCard(std::forward<CreditCard>(creditCard))
{ }

This will cause a move-construction of creditCard, which is what you want (because the value being passed is an rvalue, and that means we are authorized to move from it).

How correctly pass parameters in controllers?

Well, finally we found the problem. The problem was in application.conf file. In my case I used next database configuration:

db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://host:port/database_name"
db.default.username = "username"
db.default.password = "password"

Also in AJAX code I remove this part: type: "POST"

Function parameter is not being passed. How to correctly pass parameter into function of another JavaScript file?

The problem is that globalVar is a global variable, but the value you are assigning to it in file2Function() is accessable only within its scope, that is why you are getting undefined, because loadDynamicData() has no access to the new value of globalVar.

You could call loadDynamicData() from file2Function() and pass getValue as an argument, but since you need to open page2 before executing loadDynamicData() it won't work.

What I suggest is you pass getValue along with your URL as a query parameter and get it from inside loadDynamicData(), it'll work fine.

SOLUTION:

function file2Function(getValue)
{
window.open("page2.html?value="+getValue);
// window.open("https://www.google.com/");
}

function loadDynamicData()
{
var url_string = window.location.href
var url = new URL(url_string);
var globalVar = url.searchParams.get("value");


var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";


var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);

}

If you want to hide the values you can use sessionStorage instead of query parameters:

function file2Function(getValue)
{
sessionStorage.setItem('value', getValue)
window.open("page2.html");
// window.open("https://www.google.com/");
}

function loadDynamicData()
{
var globalVar = sessionStorage.getItem('value')

var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";


var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);

}

How to pass parameter to function inside react component..?

If I'm understanding your question correctly, you are wanting to call validateUser to conditionally set the hidden prop being passed to the div. Instead of passing an anonymous callback just directly invoke validateUser and pass the return value as the hidden prop value.

export function validateUser(data) {
return data === 'order/view';
}
export default validateUser();

...

return (
<div hidden={validateUser('order/view')}>Some Data</div>
)

or if you really are conditionally rendering some content

return validateUser('order/view') ? (
<div>Some Data</div>
) : null

How to pass parameters to function without calling function?

const _validations = {
userID: () => check('userID').isString().isUUID('4'),
};

Then you push the functions without calling them:

fieldsFound.push(_validations[key]);

And then at the end just call each one with req and await the promises returned:

await Promise.all(fieldsFound.map(func => func().run(req));

Correctly passing parameters to setTimeout

You're approaching this inside-out. When you want to incorporate non-promise async code (such as setTimeout) into your promise-based code, you should isolate the wrapped non-promise part instead of getting it mixed too deep in the rest of your promise code.

Promise wrapper for setTimeout:

function delay(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}

Then you can use it:

return Promise.props(data)
.then(function (result) {
return delay(1000).return(result);
});

Since you appear to be using Bluebird, you can also skip all the setTimeout stuff and use the built-in .delay method:

return Promise.props(data).delay(1000);

Note that either of the above will add an additional 1 second delay to the time it takes to resolve all of the promises in data. If your goal is to just make it so that the minimum total time is 1 second, then you can use my approach from this question:

return Promise.delay(1000).return(Promise.props(data));

How can I pass parameters to PHP files correctly

As I understood you post the request like this from Android App

String url = "http://blabla.org/AndroidMusicDownload/downloads/getMusic.php?canzone=" + canzone;

But there is a problem that you send 'canzone' in URL, so this is GET parameter, and in the PHP you grab this variable from $_POST, just change $_POST to $_GET, should work



Related Topics



Leave a reply



Submit