Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I used clang3.3 with netbeans on linux. All in C++11. And I have a question about initialization
int main()
{
int i();
}
The following code is compiled but not work properly. This value will not defined by debugger and cannot be printable. I wanted describe int with default value. Instead I can write "int{}" and it will be a perfect default initialization. But I want understand what I wrote here, just want.
Second question. Its about lambda. I want to know how lamda can be described without auto keyword.
auto lambda = [&]()mutable->int{};
Simple, what I can write here instead auto and compiler will not give me an error ? I just want understand.
Ad 1.
You've been bitten by the most vexing parse. Basically, C++ grammar causes ambiguities between statements and declarations in certain cases. In such cases, the input is interpreted as a declaration. Since int i() can be interpreted as an integer variable definition, or a function declaration, it is interpreted as a declaration of parameterless function i, returning int.
Ad 2.
As for the second question, C++11 Standard §5.1.2/3 says it all:
The type of the lambda-expression (...) is a unique, unnamed non-union class type — called the closure type (...)
So, there is no way to refer to it other than using auto.
Thats not a variable default initialization, its a function declaration, thanks to most-vexing-parse.
In a few words, the standard says if an expression can be evaluated as a function declaration, or as something else, it will be evaluated as a function declaration.
In your case, a function a without parameters and int as return value.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
This is a simple question, but I couldn't find the answer through searching online. I was trying to work through some leetcode problems to better my understanding of C++. I was wondering if someone could walk me through the meaning behind the creation of this function.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
}
};
I understand that public is used so that we can access ____ outside the Solution class, but I am not sure what exactly... it also looks like we are initializing a vector of integers named "twoSum" with the arguments of a vector of numbers and a target value... I was wondering what the meaning of the & is... etc. I guess a simple question would be can someone translate this block of code so that I can write my own versions for various problems (it seems like this is a constant block (or variation of a similar block) of code that is common throughout these leetcode problems).
The shown code snippet, defines a member function named twoSum that has the return type of vector<int> and has 2 parameters. The first parameter named nums is an lvalue reference to a non-const vector<int> while the second parameter named target is an int.
I was wondering what the meaning of the & is
The & in the first parameter nums of the member function means that nums is an lvalue reference to a non-const vector<int>. Meaning, the argument that will be passed to the nums parameter, will be passed by reference instead of passed by value. That is, inside the member function twoSums, the nums refer to the original vector<int> that is passed as an argument.
Also note that there should be a return statement inside the member function since the return type of the member function is non-void.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
If I have 2 functions like follows:
template <typename T>
void A(int n)
{
T a[n]; // need to use this array of variables in function B without any passing
// assignment of values to a[n] variables and rest of code for function A
}
void B()
{
// need to use a[n] array here without passing
}
Can the static array T a[n] be used in function B somehow without passing the arguments to B explicitly?
Is it called function forwarding or perfect forwarding in C++?
I'm aware that creating attempting to create a static array out of a variable int isn't standard C++ and some compilers support it. My main question is can the arguments be used in B without passing?
No. Functions have a scope, names of automatic variables are inaccessible outside of that scope, and other functions are outside of that scope.
Is it called function forwarding or perfect forwarding in C++?
No, what you're asking about is not related to forwarding. Forwarding is passing of arguments which is the opposite of what you are asking for.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The C++ standard does not allow "= initializer-clause" form of brace-or-equal-initializer (see [dcl.init]) in mem-initializer (see [class.base.init]). For example:
struct Foo {
int x;
Foo(int y): x = y {
}
};
gives a compile-time error.
Why is that? Would there be some syntactic ambiguity if such a construct was allowed? If not, were or are there proposals to add this feature to the language?
Update. The semantics I would expect of such an initializer in this context is the same as of it in context of usual variable initialization. In my opinion, that would make initialization syntax of the language more consistent.
Update 2. As pointed out by NathanOliver, if the initialization of a member does not depend on the selected constructor and/or constructor parameters, this member can be initialized through a default member initializer (see [class.mem]). But if it does, it leaves us with using direct or list initialization.
Like others have said, it's simple not an allowed syntax in ctor initialization.
Note that, for non-primitive classes, the ctor() : xyz(...) form of initialization is actually a ctor call on the type of the member xyz. While the ctor(): xyz{...} is for aggregate initialization of either an array/list or for member initialization of structs/unions that have no ctors.
A ctor() : xyz = something would seem to have to do two things: 1) a default ctor call and 2) then call the operator= for the type of member xyz all of which would be double initialization. That is probably why it is disallowed. Of course, for non-primitive cases, I guess it could be reduced to a copy-ctor call to eliminate the double initialization.
Now, you could maybe convince some that allowing it for primitive types only would be ok, but that would likely introduce other complications into the language and compilers.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
OK, I know this looks like a duplicate of Why do functions need to be declared before they are used? but it doesn't seem like existing answers fully address all the details.
I know that C++ was originally designed in the 80's so it could be translated in a single pass, because computers were slow. OK. But the most recent standard was published in 2011, so I don't see why C++ compilers can't do things now that require multiple passes. It would still hurt performance, yes, but only if it actually became necessary. So the following would still only require a single pass:
void foo();
int main() { foo(); }
void foo() {}
whereas for the following, the compiler could make two (and be slower), because it doesn't know whether foo is a function or a type until it sees the declaration below:
int main() { foo(); }
void foo() {}
and if you tried to use a function without declaring it first, and the declaration is not in the current translation unit at all, then it would be an error. But if it's in the same translation unit then the compiler could just make additional passes.
My colleague argues that such a feature would save a lot of developer time, and would avoid issues with the declaration and definition not being matched. And I'm sure this has been proposed many times over and rejected every time. What is the actual reasoning behind rejecting it, i.e., the committee's rationale?
Template parsing
Consider the following line of code:
a < b , c > d;
How would you parse this? There are actually two ways, depending on what a, b, c and d are. Firstly, a variable declaration
a<b,c> d;
^^^^^^ ^
Type Var
in the case that a is a known template type, b and c are other known types. Secondly,
a<b , c<d ;
^^^ ^^^
boolean expressions
in the case that a, b, c and d are all variables of some sort.
The vexing parse
Or here another one:
a b(c); // is 'b' a function or a variable?
This could be a function declaration (a function with return type a and argument type c) or a variable definition (whose type is a and whose constructor argument is c).
Conclusion
There's a lot of stuff like that, unfortunately. I'm not sure, if it would be impossible to write a compiler that can deal with that kind of stuff, but it would at least be very hard to write one. Compilation times are a serious issue in C++ already. This would only make it worse. Also: It is good practice to only use what you have defined or declared already, even in other languages.
Constraints of the committee
Even if it would be reasonably possible to implement this feature, it would kill backwards compatibility. Function overloading resolution only takes prior declarations into account and the interpretation of function calls may change depending on the place a function call is written. That's the way C++ is put together. Now, the C++ standards committee is big on back-wards compatibility. In particular: They do not want to break any existing code (and rightly so). Your proposal would surely break existing code which is a no-go for the language designers.
The current answer is because it would be unparseable.
Consider two-phase name lookup for templates, and in particular the need for typename. In templates, type-dependent names may not have been declared yet. To be able to parse them, we absolutely need typename. Without that, parsing would grind to a halt and we can't reliably proceed, so we couldn't even provide the type needed to fix the parsing problem. It's a chicken and egg problem: If we need to have parsed line 10 to parse line 5, line 10 will never be parsed because we break at line 5. typename helps us get past line 5 so we can learn the actual type on line 10.
Here, we'd have a similar problem. Consider this code under your assumptions:
struct Foo { };
int bar () { return Foo(); }
int Foo () { return 42; }
To parse this code, we need to know whether Foo denotes a type or function.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
When should we use default parameters? What is the proper syntax and where should they not be used? Is using them regularly a good or a bad habit? Do they affect efficiency?
Only case I can think of where it affects efficiency would be when you include something big as a default parameter but it's not used by any of the callers. For example:
#include <iostream>
void foo(std::ostream& out=std::cout) {
out << "foo";
}
If none of the callers use the default parameter, and the rest of the program doesn't need <iostream> then it will have been included in vain, increasing the executable size (and compilation time which may or may not matter much).
The proper syntax may be found in any C++ reference, e.g. http://msdn.microsoft.com/en-us/library/91563f79.aspx. They should never have any efficiency impact. As for usage hints, as with everything else it depends on specific case. They may make things cleared or more complicated.
One more thing worth mentioning - one should be careful with default parameters in virtual functions, since their values are resolved based on the static type, which can be unexpected.
The default value of a parameter is specified only in the declaration of a (member) function, like so:
void fun(int value = 0);
Note that only the final parameters in a parameter-list may have default-values. E.g. the following is forbidden:
void fun(int v1 = 0, int v2);
When the function is defined somewhere else, the default value must be omitted.
void fun(int value)
{
cout << value << '\n'; // will print 0 when nothing was passed by the user
}
They do not have runtime-overhead in any way, as the compiler will add this value to the function-call when the user has not specified it. Use them only when a certain default behavior is intuitive.
It can sometimes serve as an alternative to function overloading. The effect of the example above could also have been achieved by
void fun();
void fun(int value);
But this means you'd have to implement fun twice (where fun() just calls fun(0)).